For loops mutating values

let mut numbers:Vec<i16> = vec![0, 1, 2];

for x in numbers.iter_mut()
{
    *x *= 2; // Why does the variable 'x' have to have the asterisk '*' symbol?
}

println!("{:?}", numbers);

My question is why does the variable x have to have the asterisk * symbol when I am mutating the number’s vector’s contents?

Check this out.

2 Likes

x is &mut i16, *x is i16.

  • *x = 1 changes value borrowed by x to 1.
  • x = &mut 1 would change x to borrow a different number, rather than the one from the vector.
  • x = 1 doesn’t compile, because the types are different. Rust tries to smooth that difference out in a few places (Deref trait), but can’t do it everywhere, because it gets really complex and ambiguous with larger types.
2 Likes

See also the type of IterMut. It’s a iterator that gives you mutable references to the data. So you gotta dereference the reference :slight_smile: