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)?
&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 theAddtrait, which has the following variants:That is, you can add any pair of references and non-references. However, your second example would have two levels of indirection (
&&i32), and theAddtrait isn't implemented for that many levels of reference.