I am confused with borrowing and ownership. In the Rust documentation about reference and borrowing
let mut x = 5;
{
let y = &mut x;
*y += 1;
}
println!("{}", x);
They say
println!
can borrowx
.
I am confused by this. If println!
borrows x
, why does it pass x
not &x
?
I try to run this code below
fn main() {
let mut x = 5;
{
let y = &mut x;
*y += 1;
}
println!("{}", &x);
}
This code is identical with the code above except I pass &x
to println!
. It prints '6' to the console which is correct and is the same result as the first code.
The macros
print!
,println!
,eprint!
,eprintln!
,write!
,writeln!
andformat!
are a special case, not behaving as normal things do for reasons of convenience. The fact that they take references silently is part of that difference.Run it through
rustc -Z unstable-options --pretty expanded
on the nightly compiler and we can see whatprintln!
expands to:Tidied a lot, it’s this:
Note the
&x
.If you write
println!("{}", &x)
, you are then dealing with two levels of references; this has the same result because there is an implementation ofstd::fmt::Display
for&T
whereT
implementsDisplay
(shown asimpl<'a, T> Display for &'a T where T: Display + ?Sized
) which just passes it through. You could just as well write&&&&&&&&&&&&&&&&&&&&&&&x
.