if x
is a &mut i32
why don't I need to print it as println!("Number: {}", *x)
?
Good question!
The answer is because, when you use the println!()
macro, references are automatically dereferenced. So the following lines are functionally equivalent:
println!("Number: {}", x); // x is a reference
println!("Number: {}", *x);
In fact, all these lines (the ones after the declaration) are equivalent, too:
let x = 5;
println!("{}", x); // prints: 5
println!("{}", &x); // prints: 5
println!("{}", &&x); // prints: 5
println!("{}", &&&x); // prints: 5
println!("{}", &&&&x); // prints: 5
println!("{}", &&&&&x); // prints: 5
println!("{}", &&&&&&x); // prints: 5
So it doesn't matter how many times I reference a reference of a reference, because when I use the println!()
macro all my references will be glady dereferenced for me.
This is convenient behavior when using println!()
, but it can cause some confusion if you don't realize you're using a reference.
EDIT: Changed wording so that it no longer explicitly says that it's the println!()
macro that is doing the dereferencing behavior.