What is the usage of the asterisk symbol in Rust?

后端 未结 1 950
小鲜肉
小鲜肉 2020-12-19 03:30

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);

相关标签:
1条回答
  • 2020-12-19 04:07

    If *y is a reference

    *y is not a reference. y is a reference; *y dereferences y, allowing you access to the referred-to value.

    what is the difference [between += and println!]

    println! is a macro that automatically references the arguments given to it. In addition, the Display trait (used via {} in the format string) is implemented for all references to types that themselves implement Display (impl<'a, T> Display for &'a T where T: Display + ?Sized).

    Thus, println!("{}", y); is actually printing out a reference to a reference to a value. Those intermediate references are automatically dereferenced due to the implementation of Display.

    +=, on the other hand, is implemented via the AddAssign trait. The standard library only implements adding an integer type to itself (impl AddAssign<i32> for i32). That means that you have to add an appropriate level of dereferencing in order to get both sides to an integer.

    0 讨论(0)
提交回复
热议问题