3

I have to implement a function that adds two numbers:

fn add(x: &i32, y: &i32) -> i32 {
    println!("x is: {}, y is {}", x, y);
    println!("*x is: {}, *y is {}", *x, *y);
    x + y
}

fn double(x: i32) -> i32 {
    add(&x, &x)
}

fn main() {
    assert_eq!(double(5), 10);
    println!("Success!");
}

The output is:

x is: 5, y is 5
*x is: 5, *y is 5
Success!

Per my understanding, the add function should not be able to perform x+y as they both are addresses. Only *x + *y should work as it dereferences the addresses and provides the values stored there. However, both statements yield the same result. Why is that?

trent
  • 25,033
  • 7
  • 51
  • 90
Aviral Srivastava
  • 4,058
  • 8
  • 29
  • 81

1 Answers1

5

The Add trait (operator +) is implemented for &i32s as well as i32s. In fact, you can have any combination:

They all do the same thing, they are there for convenience.

See also:

kmdreko
  • 42,554
  • 6
  • 57
  • 106
  • Also, the `println!` macro ultimately expands to a method call—and, as with any method call, Rust recursively performs deref coercion on its arguments until it reaches the expected type (in the case of the `{}` format specifier, this is anything that implements the `Display` trait). – eggyal Jan 31 '21 at 07:15