“由于值具有类型而发生移动”Rust 错误

Gio*_*nni 5 rust

我正在学习 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());


}
Run Code Online (Sandbox Code Playgroud)

由于错误,代码无法编译:

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

我的猜测是问题在于value()

我公开了结构的内部值,但我无法真正理解问题出在哪里以及如何解决它。

我的目标是BagEntry拥有该值,但我想安全地将其暴露在结构之外

Leś*_*ajs 5

基本上发生了什么:

  pub fn value(self)->T {
      self.value
  }
Run Code Online (Sandbox Code Playgroud)

-> T意味着您要将结构体字段移出结构体。这很好,但你不能再使用你的对象了。您可以验证这一点 - 您不能连续调用println!("{}", my_bagentry.value());两次 - 在第一次调用后my_bagentry无效。

如果我理解正确的话,你只想借用对象的值。为此,您需要将方法签名更改为借用一个

pub fn value(&self)-> &T {
    &self.value
}
Run Code Online (Sandbox Code Playgroud)

现在,调用将仅借用对象,并且生成的引用将具有该借用的生命周期。