我定义了一个 Attribute
输入,我有一个 Vec<Attribute>
我正在循环检索“最佳”的那个。这与我的第一次尝试类似:
#[derive(Debug)]
struct Attribute;
impl Attribute {
fn new() -> Self {
Self
}
}
fn example(attrs: Vec<Attribute>, root: &mut Attribute) {
let mut best_attr = &Attribute::new();
for a in attrs.iter() {
if is_best(a) {
best_attr = a;
}
}
*root = *best_attr;
}
// simplified for example
fn is_best(_: &Attribute) -> bool {
true
}
我有以下编译错误:
error[E0507]: cannot move out of borrowed content
--> src/lib.rs:17:13
|
17 | *root = *best_attr;
| ^^^^^^^^^^ cannot move out of borrowed content
在搜索了一些解决方案之后,我通过执行以下操作解决了错误:
- 添加
#[derive(Clone)]
归于我的Attribute
结构 - 用
*root = best_attr.clone();
替换最终语句
我不完全理解为什么会这样,我觉得这是对我遇到的问题的粗略解决方案。这是如何解决错误的,这是解决此问题的正确方法吗?
最佳答案
您正在体验 Rust 内存模型的基础:
- 每个对象都可以(而且必须!)只属于另一个对象
- 大多数类型从不隐式复制并且总是移动(有一些异常(exception):实现
Copy
的类型)
以这段代码为例:
let x = String::new();
let y = x;
println!("{}", x);
它产生错误:
error[E0382]: borrow of moved value: `x`
--> src/main.rs:4:20
|
3 | let y = x;
| - value moved here
4 | println!("{}", x);
| ^ value borrowed here after move
|
= note: move occurs because `x` has type `std::string::String`, which does not implement the `Copy` trait
x
,属于 String
类型,不可隐式复制,因此已被移动到 y
中。 x
不能再使用了。
在您的代码中,当您编写 *root = *best_attr
时,您首先取消对引用 best_attr
的引用,然后将取消引用的值分配给 *root
。您的 Attribute
类型不是 Copy
,因此该分配应该是一个move。
然后,编译器报错:
cannot move out of borrowed content
事实上,best_attr
是一个不可变引用,它不允许让您拥有它背后的值的所有权(它甚至不允许修改它)。允许这样的移动会使拥有引用后面的值的对象处于未定义状态,这正是 Rust 旨在防止的。
在这种情况下,您最好的选择确实是创建一个与第一个对象具有相同值的新对象,这正是特征 Clone
是为了。
#[derive(Clone)]
允许您将结构标记为Clone
-able,只要它们的所有字段都是Clone
。在更复杂的情况下,您必须手动实现特征。
关于reference - 如何从 for 循环中检索用户定义的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26942358/