我刚刚开始学习一点 Rust,并且对变量可变性的概念非常感兴趣。
我正在尝试编写与这个 C++ 程序非常相似的东西。
#include <cstdio>
void do_something(int &var) {
var++;
}
int main() {
int a = 3;
int b = a;
printf("a is %d and b is %d\n", a, b);
do_something(b);
printf("a is %d and b is %d\n", a, b);
return 0;
}
我希望看到:
a is 3 and b is 3
a is 3 and b is 4
这个想法是,按引用传递使 b
可变,但 a
不是可变的。
以下是我假设如何用 Rust 编写这个程序:
fn main() {
let a: i32 = 3;
let b: &mut i32 = &a;
println!("a is {} and b is {}", a, b);
do_something(b);
println!("a is {} and b is {}", a, b);
}
fn do_something(var: &mut i32) {
(*var)+=1;
}
但是,由于不匹配的可变性,我得到了错误。
error: mismatched types:
expected
&mut i32
, found&i32
(values differ in mutability) [E0308]
有没有办法在没有 ::New
的情况下在 Rust 中保护这种按引用传递的样式?我的猜测是我可以使用 .clone()
,但我不确定。
最佳答案
您误解了代码的作用。这是实际的等效代码:
fn main() {
let a: i32 = 3;
let mut b = a;
println!("a is {} and b is {}", a, b);
do_something(&mut b);
println!("a is {} and b is {}", a, b);
}
fn do_something(var: &mut i32) {
*var += 1;
}
b
在您的 C 代码中不是任何形式的引用;它与 a
完全没有关系。只是 C 允许您传递一个值并让它推断它必须引用它,而 Rust 对此类事情非常明确,因此您需要编写 &mut b
而不是只是 b
将可变引用传递给 do_something
。前面的 mut b
只是让 b
槽可变,允许你改变它里面的值(没有它,你将无法创建对b
).
关于rust - 如何对不可变值进行可变引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31713130/