[英]'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.