【发布时间】:2021-07-16 05:07:15
【问题描述】:
当为结构使用Arc<Mutex<>> 包装器时,是否可以将包装器解引用到内部结构字段之一中?在这种情况下,我想将我的 PersonWrapper 结构体从内部 PersonStruct“名称”字段中转换为 String。
use std::sync::{Mutex, Arc};
pub struct PersonWrapper{
inner: Arc<Mutex<Person>>
}
impl PersonWrapper{
pub fn new(name: String, age: i32,)->Self{
PersonWrapper{
inner: Arc::new(Mutex::new(Person::new(name, age)))
}
}
}
pub struct Person{
name: String,
age: i32,
}
impl Person{
pub fn new(name: String, age: i32)->Self{
Person{
name,
age,
}
}
}
impl std::ops::Deref for PersonWrapper{
type Target = String;
fn deref(&self) -> &Self::Target {
&self.inner.into_inner().unwrap().name
// &self.inner.lock().unwrap().node_id.clone()
}
}
fn main(){
let wrapped_person = PersonWrapper::new(String::from("Zondo"), 45);
assert_eq!(*wrapped_person, String::from("Zondo"));
}
给出错误:
error[E0515]: cannot return reference to temporary value
&self.inner.into_inner().unwrap().name
^--------------------------------^^^^^
||
|temporary value created here
returns a reference to data owned by the current function
error[E0507]: cannot move out of an `Arc`
&self.inner.into_inner().unwrap().name
^^^^^^^^^^ move occurs because value has type `Mutex<Person>`, which does not implement the `Copy` trait
【问题讨论】:
-
忽略
Arc/Mutex问题,将Deref用于Person的名称中,我认为是滥用该特征。目前尚不清楚为什么一个人应该表现得好像它是一个字符串并允许像person.is_empty()这样的东西。 -
我明白了。我想我以前见过这样使用它,但在这种情况下这可能没有意义。我只是希望能够轻松访问
name字段。
标签: rust