What's the meaning of let b = &mut a?

I am learning rust recently and encountered a concept problem.

fn main() {
    let mut a = String::from("hello");
    let b = &mut a;                                                             
    println!("{}", b); 
    println!("{}", a); 

here, b is a mutable reference of a. But I can't change the mutable variable a anymore until the lifetime of b is over.
so What's the difference between
let b = &a and let b = &mut a;
Because both a and b are not mutable.

I don't understand the problem – the variable a is definitely mutable. If you have a mutable borrow to it, you can modify it through b, by dereferencing it. E.g. to set it to another string, write: *b = String::from("another string");

However, it is a feature of Rust that you can only ever change a value from one place. That is, you can only have at most one mutable borrow at any point in time (and you might not have mutable and immutable borrows at the same time). That is half of the mechanism that prevents Rust programs from making memory management mistakes like double-free or iterator invalidation. Those errors arise from looking at an object while it is being changed.

In contrast, you can have any number of immutable borrows to the same object, because nothing can go wrong by merely observing the current, non-changing state of an object from several different places.

Thanks for your reply.
I mean I can't change a directly, like a = String::from("world"), after I defined b.
So I feel a bit strange what's the mut means in let b = &mut a;

I'm not sure what you are getting at. let b = &mut a; means that b is a mutable reference to a. It does not mean that a is mutable. The fact that a is mutable is due to it being declared as let mut a = …. (Of course, you can take a mutable reference to a only if it is mutable, so let b = &mut a; compiling successfully implies indirectly that a was declared as let mut a = …, but that's not the point.)

The variables a and b are different entities. That's exactly what I explained above. Consequently, the two muts are in different contexts – one designates the mutability of the variable a, and the other one designates the fact that b is pointing to a mutable value.

If you remove the mutable borrow or restrict its scope to something shorter than the scope of a, you can change a directly. Playground. But I repeat, the fact that you are not allowed to do this while there is a mutable borrow is one of the core features of Rust.

Here are some examples which will hopefully help highlight what the mut means and the difference between b being a &mut and b itself being mutable.

1 Like

Thanks very much!