问题描述
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);
}
为什么 number + number
失败而 number.add(number)
有效?
Why does number + number
fail but number.add(number)
works?
作为一个额外的问题:上面打印出来
As a bonus question: The above prints out
10
5
我是否正确地假设 test
仍然是 5,因为数据被复制以递增?原始 test
变量可以被 increment
函数改变的唯一方法是将其作为 Box
发送,对吗?
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
失败,因为它们是两个引用,而不是两个整数.编译器还告诉我们原因:+
运算符没有为 &mut int
类型实现.
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
.
您必须使用取消引用运算符 *
取消引用才能获得 int.这会起作用 let sum = *number + *number;
You have to dereference with the dereference operator *
to get at the int. This would work let sum = *number + *number;
number.add(number);
起作用是因为 add 的签名是 fn add(&self, &int) ->int;
number.add(number);
works because the signature of add is fn add(&self, &int) -> int;
我认为 test 仍然是 5 是否正确,因为数据被复制了结束增加?原始测试变量的唯一方法被增量函数改变的情况是,如果它被发送为盒子,对吧?
Test 没有被复制过来,但仍然是 5,因为它实际上从未发生过变异.如果你愿意,你可以在 increment 函数中改变它.
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:改变它
fn increment(number: &mut int) {
*number = *number + *number;
println!("{}", number);
}
这篇关于为什么二元 + 运算符不适用于两个 &mut int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!