我试图在可以通过引用改变的特征中有一个值。问题是String
值非常大,可能被许多线程访问,所以我的解决方案看起来像这样:
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
?
好好看看RwLock
的界面。
get_mut
返回一个LockResult<&mut T>
,它是一个保护对象。这个守卫的破坏会自动解锁锁。
为了安全起见,你通过呼叫守卫unwrap()
得到的&mut T
是向守卫借来的,也就是说,unwrap()
结果的寿命受到守卫的限制(因为在守卫被摧毁后,锁是解锁的)。
在这里,您正在创建一个临时防护并立即将其丢弃,因此引用的生存期不能超过函数的生存期......
恭喜生锈!在编译时阻止了另一个数据竞争:)