我正在学习Rust,遇到了一些令人困惑的问题。以下代码可以编译并且按预期工作(编辑:添加了除测试函数外的代码,此前被省略):
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;
在正确的示例中,为什么此时 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
当我不明确定义类型时,我的代码出现了移动操作,而在其他情况下则是借用操作。发生了什么?如何在明确给定类型的同时获得与以前相同的行为?是什么原因导致了一种情况下的移动操作,而另一种情况下则是借用操作呢?
带有完整程序的编辑