简体   繁体   English

'移动发生是因为值具有类型' Rust 错误

[英]'move occurs because value has type' Rust error

I'm learning Rust and I don't udestrand what is the problem of the following code我正在学习 Rust,但我不明白以下代码的问题是什么

pub enum BagEntryState {
    UNUSED, USED, REMOVED
}

impl PartialEq for BagEntryState {
    fn eq(&self, other: &Self) -> bool {
        self == other
    }
}

pub struct BagEntry< T: std::cmp::PartialEq + fmt::Display> {
    state : BagEntryState,
    value: T,
}

impl<'a, T: std::cmp::PartialEq + fmt::Display> BagEntry<T> {
    pub fn new(value: T) -> BagEntry< T> {
        BagEntry {
            value,
            state: BagEntryState::UNUSED,
        }
    }

    pub fn value(self)->T {
        self.value
    }
}

impl<'a, T: std::cmp::PartialEq + fmt::Display> PartialEq for BagEntry<T> {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value
    }
}

impl<T: std::cmp::PartialEq + fmt::Display> fmt::Display for BagEntry<T> {
    // This trait requires `fmt` with this exact signature.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.value)
    }
}

use core::fmt;


fn main() {

    let my_bagentry = BagEntry::new(String::from("ciao"));
    //println!("{}", my_bagentry.value());
    let mut contVec : Vec<BagEntry<String>>=vec![];
    contVec.push(my_bagentry);
    println!("state ={}", contVec[0]);
    println!("state ={}", contVec[0].value());


}

The code is not compiling becaus of the error:由于错误,代码未编译:

54 |     println!("state ={}", contVec[0].value());
   |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ move occurs because value has type `BagEntry<std::string::String>`, which does not implement the `Copy` trait

My guess is that the problem is that with value()我的猜测是问题在于value()

I'm exposing the struct inner value, but I cannot really understand where the problem is and how to solve it.我暴露了 struct 内部值,但我无法真正理解问题出在哪里以及如何解决它。

My aim is that BagEntry owns the value but I want safely expose it outside the struct我的目标是BagEntry拥有该值,但我想安全地将它暴露在结构之外

Basically what is happening:基本上发生了什么:

  pub fn value(self)->T {
      self.value
  }

Here -> T means that you are moving the struct field out of the struct.这里-> T表示您正在将结构字段移出结构。 This is fine, but you cannot use your object anymore.这很好,但您不能再使用您的对象。 You can verify this - you cannot call your println!("{}", my_bagentry.value());您可以验证这一点 - 您不能调用println!("{}", my_bagentry.value()); twice in a row - after the first one the my_bagentry is invalidated.连续两次 - 在第一次之后my_bagentry失效。

If I understand correctly you want only to borrow the value out of the object.如果我理解正确,您只想从对象中借用价值。 To do this you need change your method signature to borrowing one .为此,您需要将方法签名更改为借用一个

pub fn value(&self)-> &T {
    &self.value
}

Now the call will only borrow on the object and the the resulting reference will have the lifetime of that borrow.现在调用只会借用对象,结果引用将具有借用的生命周期。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Rust 编译错误:'发生移动是因为 `self.styles` 的类型为 `HashMap&lt;&amp;str, &amp;str&gt;`' - Rust compilation error: 'move occurs because `self.styles` has type `HashMap<&str, &str>`' Rust:发生移动是因为类型为 `ReadDir`,它没有实现 `Copy` 特征 - Rust: move occurs because has type `ReadDir`, which does not implement the `Copy` trait 发生 Rust 文件树移动是因为 `subtree` 的类型为 `trees::Tree<PathBuf> `,它没有实现 `Copy` 特征 - Rust File Tree move occurs because `subtree` has type `trees::Tree<PathBuf>`, which does not implement the `Copy` trait 移动发生是因为值的类型为 Vec<T> ,它没有实现 `Copy` 特性 - move occurs because value has type Vec<T>, which does not implement the `Copy` trait move 发生是因为 value 的类型为 `RefCell&lt;…&gt;`,它没有实现 `Copy` 特征 - move occurs because value has type `RefCell<…>`, which does not implement the `Copy` trait 由于 `slice[_]` 的类型为 `T`,它没有实现 `Copy` 特征,因此无法移出此处发生移动 - Cannot move out of here move occurs because `slice[_]` has type `T`, which does not implement the `Copy` trait 无法移出位于共享引用移动后面的 `*handle`,因为 `*handle` 具有类型 - cannot move out of `*handle` which is behind a shared reference move occurs because `*handle` has type “由于在生成器中使用而发生移动”错误在 Rust 中意味着什么? - What does `move occurs due to use in generator` error mean in Rust? 如何避免“由于`v`的类型为`Vec而发生移动<char> `,它没有在循环中实现`Copy` trait&quot; - How to avoid "move occurs because `v` has type `Vec<char>`, which does not implement the `Copy` trait" within loop Rust:“不能移出`self`,因为它是借来的”错误 - Rust: “cannot move out of `self` because it is borrowed” error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM