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 of y, making *y, because y &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

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -