3

我有一个包含RefCell包装 a的结构TlsStream<TcpStream>。我测试了TlsStream<IO>用 an替换i32并且能够改变结构成员,但是在使用流时编译器出错。尝试写入时出现以下错误:

error[E0596]: cannot borrow data in a `&` reference as mutable
  --> src/main.rs:18:9
   |
18 | /         self.i
19 | |             .tcp4_stream
20 | |             .borrow_mut()
21 | |             .as_ref()
22 | |             .unwrap()
   | |_____________________^ cannot borrow as mutable

MCVE:

[package]
name = "mvce"
version = "0.1.0"
authors = ["Joshua Abraham <sinisterpatrician@gmail.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
async-std = "1.6.3"
async-tls = "0.9.0"
use async_std::net::TcpStream;
use async_std::prelude::*;
use async_tls::client::TlsStream;
use std::{cell::RefCell, rc::Rc};

#[derive(Default, Clone)]
struct Client {
    i: Rc<ClientInternal>,
}

#[derive(Default)]
struct ClientInternal {
    tcp4_stream: RefCell<Option<TlsStream<TcpStream>>>,
}

impl Client {
    async fn send(&self) {
        self.i
            .tcp4_stream
            .borrow_mut()
            .as_ref()
            .unwrap()
            .write_all(b"hello world!")
            .await;
    }
}

fn main() {
    println!("Hello, world!");
}

我如何在这里利用内部可变性?

4

0 回答 0