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?
A binary operator is an operator that operates on two operands and manipulates them to return a result.
binary operator * cannot be applied to operands of type Int and Double.
In Boolean algebra, the binary operator produces an output of 1 (true) when both the inputs are 1 (true) and 0 (false) in all other cases.
There are three types of binary operators: mathematical, logical, and relational. There are four basic mathematical operations: addition (+), subtraction (-), multiplication (*), and division (/). In addition, the modulus operation (MOD) finds the remainder after division of one number by another number.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With