此代码可以在Rust 1.27.2中正常工作:
struct X {
a: String,
b: String,
}
impl X {
fn func(mut self: Self) -> String {
let _a = self.a;
self.a = "".to_string();
self.b
}
}
fn main() {
let x = X {
a: "".to_string(),
b: "".to_string(),
};
x.func();
}
现在使用相同的编译器版本将X
实例装箱。即使不尝试突变部分对象,借位检查器也会在self
之后停止推理:
struct X {
a: String,
b: String,
}
impl X {
fn func(self: Box<Self>) -> String {
let _a = self.a;
self.b
}
}
fn main() {
let x = Box::new(X {
a: "".to_string(),
b: "".to_string(),
});
x.func();
}
错误消息:
error[E0382]: use of moved value: `self`
--> src/main.rs:9:9
|
8 | let _a = self.a;
| -- value moved here
9 | self.b
| ^^^^^^ value used here after move
|
= note: move occurs because `self.a` has type `std::string::String`, which does not implement the `Copy` trait
是设计使盒装对象不能部分借用还是在借用检查器正在进行的重构中回归?