如何将Option <Arc <T >>取消引用为可变?

时间:2019-07-23 10:05:32

标签: rust

我想为我的项目写一些代码。如何正确取消对Option<Arc<T>>的引用?

我尝试过:

use std::io::Read;
use std::sync::Arc;

struct Map<T: Read> {
    shared_reader: Option<Arc<T>>,
}

impl<T: Read> Default for Map<T> {
    fn default() -> Self {
        Self {
            shared_reader: None,
        }
    }
}

impl<T: Read> Map<T> {
    fn read_raw_data(&mut self) -> Option<Vec<u8>> {
        if let Some(srd) = &mut self.shared_reader {
            /*I think the srd should have a type &mut Arc<T>*/
            let mut buf = Vec::with_capacity(4096);
            if let Ok(_) = srd.read_to_end(&mut buf) {
                return Some(buf);
            } else {
                return None;
            }
        } else {
            return None;
        }
    }
}

编译时,出现错误:

error[E0596]: cannot borrow data in a `&` reference as mutable
  --> src/lib.rs:21:28
   |
21 |             if let Ok(_) = srd.read_to_end(&mut buf) {
   |                            ^^^ cannot borrow as mutable

有解决方法

use std::borrow::BorrowMut;
use std::io::Read;
use std::sync::{Arc, Mutex};

struct Map<T: Read> {
    shared_reader: Option<Arc<Mutex<T>>>,
}

impl<T: Read> Default for Map<T> {
    fn default() -> Self {
        Self {
            shared_reader: None,
        }
    }
}

impl<T: Read> Map<T> {
    fn read_raw_data(&mut self) -> Option<Vec<u8>> {
        if let Some(srd_lock) = &self.shared_reader {
            if let Ok(srd) = &mut srd_lock.lock() {
                let mut buf = Vec::with_capacity(4096);
                if let Ok(_) = srd.read_to_end(&mut buf) {
                    return Some(buf);
                } else {
                    return None;
                }
            } else {
                return None;
            }
        } else {
            return None;
        }
    }
}

0 个答案:

没有答案