无法重新借用变量,因为我无法将不可变的本地变量作为可变变量进行借用。

7

我刚接触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);
}
1个回答

8

consume_two_bytes函数中,reader必须是可变的:

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

谢谢!我从来没有想过在不使用&的情况下使用mut。这是我自己的一些严重的隧道视觉问题。 - Donald H
@DonaldH 是的,mut 出现在不同的位置有点不直观。 - fjh
1
直到你习惯了它,它才变得直观起来。许多人指出,语法与“let”绑定/模式绑定相似。 - Shepmaster
1
请注意,这在本例中有效是因为存在 impl<'a, R: Read + ?Sized> Read for &'a mut R(即对实现了 Read 的类型的可变引用也实现了 Read)。但这并不一定适用于其他特征。 - Francis Gagné

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接