简体   繁体   English

如何在 RwLock 中获取对 object 的引用?

[英]How to get a reference to the object inside an RwLock?

This code works:此代码有效:

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);
}

I want to get rid of the .clone() as foo in my program is 100MB+, and I need to take this reference many times.我想摆脱.clone()因为我的程序中的foo是 100MB+,我需要多次引用这个引用。

When I get rid of .clone() I get the error:当我摆脱.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`

I want to serialise foo (from another thread, in the real code, hence the Arc).我想序列化foo (从另一个线程,在真实代码中,因此是 Arc)。

How can I get an &Foo from lock , without the wasteful .clone() ?如果没有浪费的.clone() ,我如何从lock获得&Foo

RWLockReadGuard derefs to the underlying type. RWLockReadGuard 引用底层类型。

There's no ron in playground so I can not check for sure, but this should do the trick:操场上没有ron ,所以我无法确定,但这应该可以解决问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM