无法重新借用变量,因为我不能将不可变的局部变量借用为可变的

Unable to re-borrow a variable because I cannot borrow immutable local variable as mutable

我是 Rust 的新手,在使用借用检查器时遇到了困难。

main 调用 consume_byte 工作正常。但是,如果我尝试在两者之间添加另一个函数 (consume_two_bytes),一切都会崩溃。

以下代码无法编译,因为 consume_two_bytes 中的 reader 变量似乎不可变且无法借用。

在函数签名中添加 &mut 只会更改编译器错误。

use std::io::Read;
use std::net::TcpListener;

fn consume_byte<R>(reader: R) where R: Read {
    let mut buffer = vec![];
    reader.take(1).read_to_end(&mut buffer).unwrap();
}

fn consume_two_bytes<R>(reader: R) where R: Read {
    consume_byte(&mut reader);
    consume_byte(&mut reader);
}

fn main() {
    let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
    let (mut stream, _) = listener.accept().unwrap();

    consume_byte(&mut stream);
    consume_byte(&mut stream);

    consume_two_bytes(&mut stream);
}

reader 必须在 consume_two_bytes 中可变:

fn consume_two_bytes<R>(mut reader: R) where R: Read { // note the mut
    consume_byte(&mut reader);
    consume_byte(&mut reader);
}