In the following rust code I am trying to change the contents of an array:
let mut example_state = [[0;8]; 2];
for mut i in example_state.iter() {
let mut k = 0;
for j in i.iter(){
i[k] = 9u8;
k +=1
}
}
However I get the error message:
src/main.rs:18:13: 18:23 error: cannot assign to immutable indexed content `i[..]`
src/main.rs:18 i[k] = 9u8;
which I'm confused by because I am defining i
to be mut
and example_state
is also mutable.
I also don't know if this is the best way to change the contents of an array - do I need the counter k
or can I simply use the iterator j
in some way?
UPDATE: So I found that this block of code works:
let mut example_state = [[n;8]; 2];
for i in example_state.iter_mut() {
for j in i.iter_mut(){
*j = 9u8;
}
}
but I would appreciate some explanation of what the difference is between them, iter_mut
doesn't throw up much on Google.
Let's look at the signatures of the two methods, iter
and iter_mut
:
fn iter(&self) -> Iter<T>;
fn iter_mut(&mut self) -> IterMut<T>;
And the structs they return, Iter
and IterMut
, specifically the implementation of Iterator
:
// Iter
type Item = &'a T
// IterMut
type Item = &'a mut T
These are associated types, but basically in this case, they specify what the return type of calling Iterator::next
. When you used iter
, even though it was on a mutable variable, you were asking for an iterator to immutable references to a type T
(&T
). That's why you weren't able to mutate them!
When you switched to iter_mut
, the return type of Iterator::next
is &mut T
, a mutable reference to a type T
. You are allowed to set these values!
As an aside, your question used arrays, not slices, but there aren't documentation links for arrays (that I could find quickly), and slices are close enough to arrays so I used them for this explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With