Using & when passing a borrowed parameter

I do not understand the difference between the following two calls in the working program below ?

add_my_size(self, rhs)
add_my_size(&self, &rhs)

struct MyUsize {
    value : usize  ,
}
fn add_my_size(left : &MyUsize, right : &MyUsize) -> MyUsize
{   MyUsize {
        value : left.value + right.value ,
    }
}
impl std::ops::Add< &MyUsize > for &MyUsize {
    type Output = MyUsize;
    fn add(self, rhs : &MyUsize) -> MyUsize {
        if self.value < rhs.value {
            add_my_size(&self, &rhs) 
        } else {
            add_my_size(self, rhs) 
        }
    }
}
fn main() {
    let one   = MyUsize{ value : 1 };
    let two   = MyUsize{ value : 2 };
    let three = &one + &two;
    println!( "&one + &two = {}", three.value);
}

There is no difference, since Rust has a feature called Deref coercion which implicitly inserts the necessary de-referencing operations. Effectively when you pass &x to a function, Rust tries &x, &*x, &**x, ... until the type matches. This is intended for smart pointers, so you can use an &String as &str or an &Arc<T> as &T, but it happens to work for nested references as well.

2 Likes