I have an 2D array, and I want a function to change it. I don't know vectors yet, but since the array is going to have a fixed size, I don't need them. I wanted to give the function a slice of an array of slices of arrays, e. g. fn my_func (arr: &mut [&mut [char]]) {...}
, but I don't know how to call it from my int main.
Here's an example I've been playing with.
fn main() {
let mut map = [['-'; 3]; 3];
for row in map {
for col in row {
print!("{} ", col);
}
println!("");
}
println!("Changing...");
put_plus(???);
for row in map {
for col in row {
print!("{} ", col);
}
println!("");
}
}
fn put_plus(map: &mut [&mut [char]]) {
map[map.len() - 1][map[map.len() - 1].len() - 2] = ' ';
}
The output I expect is:
- - -
- - -
- - -
Changing...
- - -
- - -
- -
Is there an expression to turn [[char; 3]; 3]
into [[char]]
so that I could put this expression instead of ???
and everything works??
CodePudding user response:
Here's a version of the plus function that works for all sizes:
fn put_plus<const COUNT: usize>(map: &mut [[char; COUNT]; COUNT]) {
map[map.len() - 1][map[map.len() - 1].len() - 2] = ' ';
}
As pointed out in the comments, you just need a mutable reference on the "outer" struct. In Rust, you don't control mutability at the "element" level. Instead, mutability of a container extends to all the elements within that container. You can't have, for example, a mutable vector containing immutable vectors or a mutable array containing immutable arrays.
So, just slapping a &mut
to the "outside" of your array means everything in your array, including the inner arrays AND the values contained within those inner arrays, will be mutable.