Reputation: 1923
It is possible to make the following binding in Rust:
let &mut a = &mut 5;
But what does it mean exactly? For example, let a = &mut 5
creates an immutable binding of type &mut i32
, let mut a = &mut 5
creates a mutable binding of type &mut i32
. What about let &mut
?
Upvotes: 13
Views: 2815
Reputation: 60197
An easy way to test the type of something is to assign it to the wrong type:
let _: () = a;
In this case the value is an "integral variable", or a by-value integer. It is not mutable (as testing with a += 1
shows).
This is because you are using destructuring syntax. You are pattern matching your &mut 5
against an &mut _
, much like if you wrote
match &mut 5 { &mut a => {
// rest of code
} };
Thus you are adding a mutable reference and immediately dereferencing it.
To bind a mutable reference to a value instead, you can do
let ref mut a = 5;
This is useful in destructuring to take references to multiple inner values.
Upvotes: 14