Arrays are different types of slices. It is noteworthy that arrays have a fixed size, known at compile time . Slices are fixed in size, but known only at runtime .
I see two straightforward options here (see Levans responsible for the other ). The first is to change your function to accept only references to arrays (or the entire array if you can copy it or not mind giving up ownership):
fn foo(a: &[[f64; 4]; 3], x: &[f64; 3]) { for i in 0..3 { for j in 0..4 { println!("{}", a[i][j]); } } } fn main() { let a = [ [1.1, -0.2, 0.1, 1.6], [0.1, -1.2, -0.2, 2.3], [0.2, -0.1, 1.1, 1.5], ]; let x = [0.0; 3]; foo(&a, &x); }
Another simple change is to make your declaration a link:
fn foo(a: &[&[f64]], x: &[f64]) { for i in 0..3 { for j in 0..4 { println!("{}", a[i][j]); } } } fn main() { let a = [ &[1.1, -0.2, 0.1, 1.6][..], &[0.1, -1.2, -0.2, 2.3][..], &[0.2, -0.1, 1.1, 1.5][..], ]; let x = [0.0; 3]; foo(&a, &x); }
Note that in this second example, we can use implicit coercion to reference a slice array when we simply pass &a and &x . However, we cannot rely on this for nested data in a . a already defined as an array of arrays, and we cannot change the element type.
Also a word of caution - you really need to use the cut length method in your ranges, otherwise you can easily panic! if you leave from the end.
fn foo(a: &[&[f64]], x: &[f64]) { for i in 0..a.len() { let z = &a[i]; for j in 0..z.len() { println!("{}", z[j]); } } }
Other stylistic changes that I made to meet the rust style:
snake_case variables- space after
: - space after
; - space around
= - space after