rust - 为什么我的扩展特性没有被 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
了,所以我认为它会自动获取我的扩展特征。我究竟做错了什么?
解决方案
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)
}
}
推荐阅读
- javascript - 状态 ReactJS 和渲染方法
- gradle - 如何定义地图
在 build.gradle - c - 可变长度数组是否以 C 中的默认 0 值开头?
- amazon-s3 - 如何在cyberduck CLI 中启用SSE-S3 (AES-256) 加密?
- bash - 如何从输出中删除行尾
- mysql - MySQL 错误 1093 - 无法在 FROM 子句中指定要更新的目标表(两个连接)
- java - xml 尖括号改为 & lt 分号
- angular - Ionic 5 Edge 浏览器侧边菜单未显示
- python - 如何读取从 arduino 串行发送的数据结构?
- docker-compose - jfrog-artifactory docker 镜像 - 由于 nofile 使用而停止