Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the binary + operator not work with two &mut int?

Tags:

rust

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?

like image 763
Christoph Avatar asked May 28 '14 20:05

Christoph


People also ask

How many operands does a binary operator work with?

A binary operator is an operator that operates on two operands and manipulates them to return a result.

Which are the binary operator Cannot be used for real data type?

binary operator * cannot be applied to operands of type Int and Double.

Is a binary operator True or false?

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.

Which operators are binary operators?

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.


1 Answers

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);
}
like image 130
A.B. Avatar answered Sep 29 '22 09:09

A.B.