我搞不懂为什么要编译这段代码:

use std::io::{Read, BufRead};

trait ReadString {
    fn read_null_terminated_string(&mut self, max_size: u64) -> std::io::Result<String>;
}

impl<R> ReadString for R
where
    R: BufRead,
{
    fn read_null_terminated_string(&mut self, max_size: u64) -> std::io::Result<String> {
        let mut buf = Vec::new();
        self.take(max_size).read_until(0, &mut buf)?;
        Ok(String::from_utf8_lossy(&buf).to_string())
    }
}

据我所知,BufRead不是Copy,BufRead::take()是:

    fn take(self, limit: u64) -> Take<Self>
    where
        Self: Sized,
    {
        Take { inner: self, limit }
    }

那么.take()肯定应该移动self,这是不允许的,因为我只有&mut self?我甚至试着用我自己的类似BufRead的特征,但我确实收到了这个错误:

cannot move out of `*self` which is behind a mutable reference
move occurs because `*self` has type `R`, which does not implement the `Copy` trait

那么为什么我不能得到BufRead的错误呢?

推荐答案

您不是在类型Self上调用take(),而是在类型&mut Self(self参数的类型)上调用它,并且它确实使用了它.这行得通,因为Read has a blanket implementation impl<R: Read + ?Sized> Read for &mut R美元.

Rust相关问答推荐

收集RangeInclusive T到Vec T<><>

trait声明中的生命周期参数

有没有办法模仿对象安全克隆?

带扫描的铁 rust 使用滤镜

使用模块中的所有模块,但不包括特定模块

新创建的变量的绑定生存期

一种随机局部搜索算法的基准(分数)

如何从ruust中的fig.toml中读取?

习语选项<;T>;到选项<;U>;当T->;U用From定义

如何重命名 clap_derive 中的子命令占位符?

为什么需要静态生命周期以及在处理 Rust 迭代器时如何缩小它?

我可以在 Rust 中 serde struct camel_case 和 deserde PascalCase

Rust Redis 中的 HSET 命令问题

Rust 中的自动取消引用是如何工作的?

rust tokio::spawn 在 mutexguard 之后等待

`移动||异步移动{...}`,如何知道哪个移动正在移动哪个?

是否可以预测堆栈溢出?

如何获得对数组子集的工作可变引用?

如何在 nom 中构建负前瞻解析器?

如何从 many0 传播 Nom 失败上下文?