0

With a 1 dimensional array it is possible to convert from a fixed sized array to a slice but is this possible with 2d array in a trivial way?

fn foo(r: &[&[usize]]) { }
let r = [[0usize; 10]; 10];
foo(&r); //<== error expected type `&[&[usize]]` found type `&[[usize; 10]; 10]`

1 Answer 1

5

There is no trivial way of doing this (for some definition of trivial). The problem is that &[&[usize]] is a slice of slices (like a jagged array), while [[0usize; 10]; 10] is a 2D array. The data in a 2D array is contiguous, a line starts after the end of the previous line and all lines have the same number of elements. In a jagged array, each line can have a different length, and this length must be stored with each line (in Rust, a slice is a length and a pointer).

That said, you can change the definition of foo (this is the best alternative, because there is no extra allocation):

// a slice of T, where T can be used as &[usize]
fn foo<T>(r: &[T])
    where T: AsRef<[usize]>
{
    for line in r {
        println!("{:?}", line.as_ref());
    }
}

fn main() {
    let r = [[0usize; 10]; 10];
    foo(&r);
}

or create a temporary vector of slices:

fn foo(r: &[&[usize]]) {
    for line in r {
        println!("{:?}", line);
    }
}

fn main() {
    let r = [[0usize; 10]; 10];
    let x: Vec<&[usize]> = r.iter().map(|v| v.as_ref()).collect();
    foo(&x);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.