我想要通过引用可以突变的特征中具有值。问题是,String
值是非常大的,可能会被很多线程访问,所以我的解决方案看起来是这样的:将Arc <RwLock>转换为&mut
trait MyTrait {
fn name<'a>(&'a mut self) -> &'a mut String;
}
struct SimpleImpl {
name: String
}
impl MyTrait for SimpleImpl {
fn name<'a>(&'a mut self) -> &'a mut String {
&mut self.name
}
}
use std::sync::{Arc,RwLock};
struct ParallelImpl {
name: Arc<RwLock<String>>
}
impl MyTrait for ParallelImpl {
fn name<'a>(&'a mut self) -> &'a mut String {
self.name.get_mut().unwrap()
}
}
fn main() {
let mut a = SimpleImpl { name: String::from("simple") };
let mut b = ParallelImpl { name: Arc::new(RwLock::new(String::from("parallel"))) };
a.name().as_mut_str();
b.name().as_mut_str();
}
这种失败
main2.rs:23:9: 23:18 error: cannot borrow immutable borrowed content as mutable
main2.rs:23 self.name.get_mut().unwrap()
编译为什么我不能请致电get_mut()
解开Arc
和RwLock
?
这看起来像['owning_ref']的另一个工作(https://kimundi.github.io/owning-ref-rs/owning_ref/index.html)箱。它包含一个['RwLockWriteGuardRef'](https://kimundi.github.io/owning-ref-rs/owning_ref/type.RwLockWriteGuardRef.html)类型,它的行为非常像引用,但保留了警卫。 –