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?
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 worklet sum = *number + *number;
number.add(number);
works because the signature of add isfn add(&self, &int) -> int;
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