【问题标题】:How to get a reference to the object inside an RwLock?如何获取对 RwLock 内对象的引用?
【发布时间】:2020-08-20 21:29:36
【问题描述】:

此代码有效:

use serde::{Deserialize, Serialize};
use std::sync::{RwLock, Arc};
use ron;

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
struct Foo {
    first: u8,
    second: u16,
}

fn main() {
    let foo = Foo {first: 1, second: 2};
    let lock = Arc::new(RwLock::new(foo));

    let state = lock.read().unwrap().clone(); // FIXME: remove clone()
    let string = ron::ser::to_string(&state).unwrap();
    println!("{}", string);
}

我想去掉.clone(),因为我的程序中foo是100MB+,我需要多次引用这个引用。

当我摆脱 .clone() 时,我得到了错误:

error[E0277]: the trait bound `std::sync::RwLockReadGuard<'_, Foo>: _::_serde::Serialize` is not satisfied
  --> src/bin/sandbox7.rs:16:35
   |
16 |     let string = ron::ser::to_string(&state).unwrap();
   |                                      ^^^^^^ the trait `_::_serde::Serialize` is not implemented for `std::sync::RwLockReadGuard<'_, Foo>`
   | 
  ::: /home/chris/.cargo/registry/src/github.com-1ecc6299db9ec823/ron-0.6.0/src/ser/mod.rs:25:8
   |
25 |     T: Serialize,
   |        --------- required by this bound in `ron::ser::to_string`

我想序列化foo(来自另一个线程,在真实代码中,因此是 Arc)。

我怎样才能从lock 获得&amp;Foo,而不用浪费.clone()

【问题讨论】:

    标签: rust reference rwlock


    【解决方案1】:

    RWLockReadGuard derefs 到底层类型。

    操场上没有ron,所以我无法确定,但这应该可以解决问题:

    let state = lock.read().unwrap();
    let string = ron::ser::to_string(&*state).unwrap();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      • 1970-01-01
      • 2012-12-25
      • 2015-02-22
      • 1970-01-01
      相关资源
      最近更新 更多