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.

2
  • 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. Commented Jul 14, 2020 at 18:09
  • yes, thanks. I understood. Commented Jul 14, 2020 at 19:45

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

While let mut x = x; isn't very common, mut parameters are more common, and let x = x; is pretty common too.
I believe let mut x = x is fairly common in a form of function params, e.g. fn f(mut self) { .. }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.