【问题标题】:Unable to re-borrow a variable because I cannot borrow immutable local variable as mutable无法重新借用变量,因为我不能将不可变的局部变量借用为可变的
【发布时间】:2015-10-16 08:05:02
【问题描述】:

我是 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);
}

【问题讨论】:

    标签: rust borrow-checker


    【解决方案1】:

    readerconsume_two_bytes 中必须是可变的:

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

    【讨论】:

    • 谢谢!我从来没有想过在没有&amp; 的情况下使用mut。这对我来说是一个严重的隧道视野。
    • @DonaldH 是的,mut 在不同的地方有点不直观。
    • 在你习惯它之前它是不直观的,然后它再次变得直观^_^。许多人指出语法与let 绑定/模式绑定的语法相似。
    • 请注意,它恰好在这种情况下起作用,因为存在impl&lt;'a, R: Read + ?Sized&gt; Read for &amp;'a mut R(即对实现Read 的类型的可变引用也实现Read)。其他特征不一定是这种情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多