What really?

I am trying to understand the Rust link.

fn main() {
    let x: i32 = 0;
    println!("{}", x+1); // this works
    println!("{}", (&x)+1); // this works
    //println!("{}", (&(&x))+1); // but this failed
}

What I get:

    1
    1

What does &it really do? Why is it added &xas a whole, but not &(&x)?

+4
source share
1 answer

&takes a reference to the operand. This can be considered a discovery of the memory address in which the value is stored.

Your example works because it is +implemented using Addtrait , which has the following options:

impl Add<i32> for i32
impl<'a> Add<i32> for &'a i32
impl<'a> Add<&'a i32> for i32
impl<'a, 'b> Add<&'a i32> for &'b i32

That is, you can add any pair of links and not links. However, your second example will have two levels of indirection ( &&i32), and the attribute Addwill not be implemented for this set of link levels.

+5
source

All Articles