How to effectively use ArrayView?

Hi All,

From this community I have learnt a lot. Now I have a new problem. I have a function which is like below,

fn test( struct1: &MyStruct, struct2: &MyStruct2) -> ArrayView1<f32> {
    let arr2: Array2 = struct1.arr;

   let res = match struct2.method {
        1 => fn1(&arr2, struct2.n); //Returns ArrayView1 by doing arr2.column(n)
        _ => fn2(&arr); //Returns Array1 by doing arr2.column(0) + arr2.column(1)

   return res;

fn start(struct1: &mut MyStruct, struct2: &mut MyStruct2) {
    let arr = test(&struct1, &struct2);
    let res = test2(arr);

Because of different return types, the match throws error. I also tried fn(&arr).view() but rust complains temp variable lost. I can convert ArrayView1 to Array1 in fn1 but I dont want to because I am working on a very huge array 15000 * 1500 and it might be a hit in performance. Also this test function is called 1000 times. So I am looking for an optimised solution.

I think there is something I should do with lifetime. But I didn't learn it yet and felt it is advanced programming

I'm assuming you are talking about the ndarray ArrayView and Array types here. In this case you could use the Cow version of those to represent either an owned array or a view into an array: ndarray::CowArray

Yes you are right. I am using ndarray. Sorry for missing that important detail

Thanks. Finally I figured out how to use the CowArray :slight_smile:

fn use_cow<'a>(input1: &'a input) -> CowArray<'a, f32, Ix1> {
    let arr = // Some function which returns Array or ArrayView
    return CowArray::from(arr);

Replace Ix1 with the required dimension.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.