2

I was going through the Rust book from the official rust website and came across the following paragraph:

Note that we needed to make v1_iter mutable: calling the next method on an iterator changes internal state that the iterator uses to keep track of where it is in the sequence. In other words, this code consumes, or uses up, the iterator. Each call to next eats up an item from the iterator. We didn’t need to make v1_iter mutable when we used a for loop because the loop took ownership of v1_iter and made it mutable behind the scenes.

If you notice the last line. It says the for loop makes a mutable variable immutable behind the scenes. If that's possible, then is it possible for us as a programmer to do the same?

Like I know it's not safe and we're not supposed to do that and stuff, but just wondering if that would be possible.

  • 1
    The sentence doesn't say, that an immutable *variable* is turned into a mutable variable. It says that ownership of the object is transferred. The receiver is the sole owner thereafter, and can do whatever it wants with it. What's happening is similar to [this](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=87020350c8602f876226fe73f7c3eeb8). – IInspectable Jul 14 '20 at 18:09
  • yes, thanks. I understood. – Jugal Rawlani Jul 14 '20 at 19:45

1 Answers1

6

It is completely fine to rebind an immutable variable to a mutable, e.g. the following code works:

let x = 5;
let mut x = x;

After the last statement we can mutate x variable. In fact, thought, there are two variables, the first is moved into the latest. The same can be done with the function as well:

fn f(mut x: i32) {
    x += 1;
}

let y = 5;
f(y);

The thing prohibited in Rust is changing immutable references to a mutable ones. That is an important difference because owned value is always safe to change comparing to a borrowed one.

Kitsu
  • 3,166
  • 14
  • 28
  • While `let mut x = x;` isn't very common, `mut` parameters are more common, and `let x = x;` is [pretty common](https://stackoverflow.com/questions/54595345/what-does-let-x-x-do-in-rust) too. – mcarton Jul 14 '20 at 16:25
  • I believe `let mut x = x` is fairly common in a form of function params, e.g. `fn f(mut self) { .. }`. – Kitsu Jul 14 '20 at 16:28