首页 > 解决方案 > 为什么我的扩展特性没有被 Cursor 识别?

问题描述

问题的最小工作示例。阅读这篇关于扩展特征的文章,我尝试实现自己的。

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

pub trait KRead {
    fn read1(&mut self) -> io::Result<i32>;
}

impl KRead for Read {
    fn read1(&mut self) -> io::Result<i32> {
        let mut buf = [0u8];
        self.read_exact(&mut buf)?;
        Ok(buf[0] as i32)
    }
}

fn main() -> io::Result<()> {
    let input_data = [47u8, 56u8];
    let mut input_buffer = Cursor::new(input_data);
    assert_eq!(47, input_buffer.read1()?);
    assert_eq!(56, input_buffer.read1()?);
    Ok(())
}

但编译失败

No method named `read1` found for struct `std::io::Cursor<[u8; 2]>` in the current scope
No method named `read1` found for struct `std::io::Cursor<[u8; 2]>` in the current scope

但是Cursor实现Read了,所以我认为它会自动获取我的扩展特征。我究竟做错了什么?

标签: rust

解决方案


impl KRead for Read {
  ...
}

如果你在最新版本的 Rust 上编译它,你应该得到一个警告。

warning: trait objects without an explicit `dyn` are deprecated

那是因为你写的其实是

impl KRead for dyn Read {
  ...
}

也就是说,你没有说“每个Read都是一个KRead”。您已经说过“特别是 trait对象类型dyn Read是 a KRead”,它更窄且用处不大。如果您想要前者,则需要使用泛型类型参数。

impl<T> KRead for T where T: Read {
    fn read1(&mut self) -> io::Result<i32> {
        let mut buf = [0u8];
        self.read_exact(&mut buf)?;
        Ok(buf[0] as i32)
    }
}

推荐阅读