如何获得对RwLock内部对象的引用?

此代码有效:

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中)。

如何在没有浪费的&Foo的情况下从lock获得.clone()

iCMS 回答:如何获得对RwLock内部对象的引用?

RWLockReadGuard derefs到基础类型。

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

let state = lock.read().unwrap();
let string = ron::ser::to_string(&*state).unwrap();
本文链接:https://www.f2er.com/1708630.html

大家都在问