Reputation: 3647
Is there any notation similar to arr[1..3][3..5]
where the first slice 1..3
selects rows, and the second slice 3..5
selects columns?
Example code
fn main() {
let arr = [[1, 2, 3, 4]; 3];
let x = arr[0][1]; // first row, second column
println!("{}", x); // 2
let row2d = &arr[0..2]; // slice of two first row, as 2d-array
println!("{:?}", row2d); // [[1, 2, 3, 4], [1, 2, 3, 4]]
let row = &arr[0..2][0]; // slice of first row, as 1d-array, [0] operates on the [0..2] slice
println!("{:?}", row); // [1, 2, 3, 4]
// wanted first column of two first rows: [[1], [1]]
// I can pick a row, then do a slice on the row
let cols = &arr[0][1..3]; // first row, as 1d-array
println!("{:?}", cols); // [2, 3]
}
Upvotes: 1
Views: 2143
Reputation: 42829
You cannot do that as in, but you can use map to iterate over subslices:
fn main() {
let arr = [[1, 2, 3, 4]; 3];
let iter = arr[0..2].iter().map(|s| &s[1..4]);
for slice in iter {
for x in slice {
print!("{} ", x);
}
println!();
}
}
Upvotes: 2