为什么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 {
...
}
也就是说,你没有说“every Readis a 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)
}
}