Why do `x + y` and `*x + *y` give the same result when x and y are references?

Viewed 103

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?

1 Answers
Related