compiler-errors - "cannot move out of borrowed content"用于 Vec 但不是 u64

标签 compiler-errors rust borrow-checker

以下代码会抛出一个错误:

struct Foo {
    a: Vec<u64>,
}

impl Foo {
    fn change_a(&mut self, new_a: Vec<u64>) {
        self.a = *choose(&self.a, &new_a);
    }
}

fn choose<'a>(x: &'a Vec<u64>, y: &'a Vec<u64>) -> &'a Vec<u64> {
    return if x > y { x } else { y };
}

fn main() {
    let mut foo = Foo { a: vec![1] };
    foo.change_a(vec![3]);
    println!("{:?}", foo.a);
}

错误是:

error[E0507]: cannot move out of borrowed content
 --> src/main.rs:7:18
  |
7 |         self.a = *choose(&self.a, &new_a);
  |                  ^^^^^^^^^^^^^^^^^^^^^^^^ cannot move out of borrowed content

This code works fine如果我更换 Vec<u64>仅包含 u64

有什么区别?

最佳答案

原始类型u64 实现Copy .这意味着 u64 具有“复制语义”:如果编译器发现我们正在尝试获取 T: Copy 的所有权,但仍在使用正在移动的值,T 将被复制。

Vec不是Copy,而是Clone,也就是说我们可以做

self.a = choose(& self.a, & new_a).clone();

解决这个问题。

Here是使用您的示例的复制语义的另一个示例

关于compiler-errors - "cannot move out of borrowed content"用于 Vec 但不是 u64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43037583/

相关文章:

c++ - 如果返回值未用于特定类型,则编译失败

swift - 类型 '[Users]'的值没有成员 'username'

rust - 有没有更漂亮的方法将字 rune 字转换为其相应的转义字符?

rust - 为什么 &str 不实现 IntoIterator?

rust - 将可变自引用传递给拥有对象的方法

rust - 如何使从对象到其孙子的生命周期约束 "pass through"?

关于假定未声明的函数的 C++ 编译器错误

collections - 如何通过结构相等检查结构集合中的结构?

rust - 替换 Rust 中的值导致 "cannot move out of borrowed content"

Java "Reached end of file while parsing"