Why does the binary + operator not work with two &

2019-02-22 02:45发布

问题:

fn increment(number: &mut int) {

    // this fails with: binary operation `+` cannot be applied to type `&mut int`
    //let foo = number + number;

    let foo = number.add(number);

    println!("{}", foo);
}

fn main() {
    let mut test = 5;
    increment(&mut test);

    println!("{}", test);
}

Why does number + number fail but number.add(number) works?

As a bonus question: The above prints out

10
5

Am I right to assume that test is still 5 because the data is copied over to increment? The only way that the original test variable could be mutated by the increment function would be if it was send as Box<int>, right?

回答1:

number + number fails because they're two references, not two ints. The compiler also tells us why: the + operator isn't implemented for the type &mut int.

You have to dereference with the dereference operator * to get at the int. This would work let sum = *number + *number;

number.add(number); works because the signature of add is fn add(&self, &int) -> int;

Am I right to assume that test is still 5 because the data is copied over to increment? The only way that the original test variable could be mutated by the increment function would be if it was send as Box, right?

Test is not copied over, but is still 5 because it's never actually mutated. You could mutate it in the increment function if you wanted.

PS: to mutate it

fn increment(number: &mut int) {
    *number = *number + *number;
    println!("{}", number);
}


标签: rust