【发布时间】:2023-03-19 17:39:02
【问题描述】:
我正在学习 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
因此,当我没有明确定义类型而是借用时,我会采取行动。发生了什么,我如何在显式给出类型时获得与以前相同的行为,以及在一种情况下导致移动行为但在另一种情况下借用的原因是什么?
已编辑完整程序
【问题讨论】:
-
嗨,对不起;这是the full code。您的示例准确地捕捉到了问题。