I'm new to Rust and I don't understand the following piece of code:
let mut x = 5;
{
let y = &mut x;
*y += 1;
}
println!("{}", x);
Explanation from the Rust site:
You'll also notice we added an asterisk (
*
) in front ofy
, making it*y
, this is becausey
is a&mut
reference. You'll need to use astrisks [sic] to access the contents of a reference as well.
If *y
is a reference, why does the following code work
fn main() {
let mut x = 5;
{
let y = &mut x;
println!("{}", y);
}
}
I know I'm not modifying the value here, but what is the difference and why
would y += 1;
not work?