我正在学习 Rust,并且遇到了一些令人困惑的行为。以下代码可以正常编译并按预期工作(edit:添加了测试函数以外的代码,之前省略):
struct Container<'a> {
contents : &'a mut i32,
}
fn main() {
let mut one = Container { contents: &mut 5 };
test(&mut one);
println!("Contents: {}",one.contents);
}
fn test<'a>(mut x : &'a mut Container) {
*x.contents += 1;
let y = x;
*y.contents += 1;
x = y;
println!("{:?}",*x.contents)
}
现在在声明中
let y = x;
类型被推断出来。因为x
属于类型&'a mut Container
,我认为这将是等效的:
let y: &'a mut Container = x;
但是当我这样做时,编译器会出现问题:
test_3.rs:25:5: 25:10 error: cannot assign to `x` because it is borrowed
test_3.rs:25 x = y;
^~~~~
test_3.rs:23:33: 23:34 note: borrow of `x` occurs here
test_3.rs:23 let y: &'a mut Container = x;
How is x
在正确工作的示例中没有借用这一点?我通过省略该行进行测试x = y;
从正确工作的版本和编译器说:
test_3.rs:24:13: 24:14 note: `x` moved here because it has type `&mut Container<'_>`, which is moved by default
因此,当我没有明确定义类型但借用其他类型时,我会采取行动。发生了什么事,如何在显式给出类型时获得与以前相同的行为,以及是什么导致在一种情况下移动行为但在另一种情况下借用?
已编辑完整程序