What does & actually do?

101 views Asked by At

I am trying to understand Rust's reference.

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 & actually do? Why can &x be added like it is an integer but not &(&x)?

1

There are 1 answers

5
Shepmaster On BEST ANSWER

& takes the reference of the operand. This can be thought of as finding the memory address that the value is stored at.

Your example works because + is implemented using the Add trait, which has the following variants:

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 references and non-references. However, your second example would have two levels of indirection (&&i32), and the Add trait isn't implemented for that many levels of reference.