What is the usage of the asterisk symbol in Rust? -
i'm new rust , don't understand following piece of code:
let mut x = 5; { let y = &mut x; *y += 1; } println!("{}", x);
explanation rust site:
you'll notice added asterisk (
*
) in front ofy
, making*y
, becausey
&mut
reference. you'll need use astrisks [sic] access contents of reference well.
if *y
reference, why following code work
fn main() { let mut x = 5; { let y = &mut x; println!("{}", y); } }
i know i'm not modifying value here, difference , why y += 1;
not work?
if
*y
reference
*y
not reference. y
reference; *y
dereferences y
, allowing access referred-to value.
what difference [between
+=
,println!
]
println!
macro automatically references arguments given it. in addition, display
trait (used via {}
in format string) implemented references types implement display
(impl<'a, t> display &'a t t: display + ?sized
).
thus, println!("{}", y);
printing out reference reference value. intermediate references automatically dereferenced due implementation of display
.
+=
, on other hand, implemented via addassign
trait. standard library implements adding integer type (impl addassign<i32> i32
). means have add appropriate level of dereferencing in order both sides integer.
Comments
Post a Comment