I have
fn plus_one(x: &i32) -> i32 {
x + 1
}
fn plus_one_star(x: &i32) -> i32 {
*x + 1
}
fn plus_one_mut(x: &mut i32) -> i32 {
x + 1
}
fn plus_one_mut_star(x: &mut i32) -> i32 {
*x + 1
}
fn main() {
let a: i32 = 5;
let mut b: i32 = 5;
println!("{:?}", plus_one(&a));
println!("{:?}", plus_one_star(&a));
println!("{:?}", plus_one_mut(&mut b));
println!("{:?}", plus_one_mut_star(&mut b));
// I expect all to print '6' as I never actually mutate b
}
第三个函数
plus_one_mut
编译失败,错误提示为:error[E0369]: binary operation `+` cannot be applied to type '&mut i32'
。为什么这个带有可变引用的函数无法编译?
x.add(1)
在所有情况下都起作用......在这种情况下,可能是强制转换发挥了作用? - Paolo Falabella&T
的行为就像T
一样。但总的来说,在使用不可变引用之前,我是否应该对它们进行解引用?或者实现大多数T
方法的&T
是非常普遍的? - turbulencetoo&self
或者没有额外修饰的self
。方法实现是采用self
还是&self
取决于函数需要做什么。我敢打赌大多数方法都采用&self
,因为它们不需要&mut self
或者self
所提供的功能。我发现很少有必要显式添加*
,通常我会等到编译器提示我添加它。 - Shepmaster