将Arc <RwLock>转换为&mut

Joh*_*rae 0 rust

我试图在一个可以通过引用变异的特征中获得一个值.问题是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();
}
Run Code Online (Sandbox Code Playgroud)

这无法编译

main2.rs:23:9: 23:18 error: cannot borrow immutable borrowed content as mutable
main2.rs:23         self.name.get_mut().unwrap()
Run Code Online (Sandbox Code Playgroud)

为什么我不打电话get_mut()打开Arc和打开RwLock

Mat*_* M. 5

更好地了解界面RwLock.

get_mut返回一个LockResult<&mut T>保护对象.该防护装置的销毁会自动解锁.

为了使事情变得安全,&mut T你通过召唤unwrap()守卫得到的就是从守卫那里借来的,也就是说,结果的寿命unwrap()受到守卫的限制(因为在守卫被摧毁之后,锁是解锁).

在这里,你正在创建一个临时警卫并立即扔掉它,所以参考的生命周期不能超过函数的寿命......

恭喜Rust!在编译时阻止了另一个数据竞争:)