无法将特质方法引入作用域

3
我有这个 lib.rs 文件。
use std::io::{ Result, Read };

pub trait ReadExt: Read {
    /// Read all bytes until EOF in this source, returning them as a new `Vec`.
    ///
    /// See `read_to_end` for other semantics.
    fn read_into_vec(&mut self) -> Result<Vec<u8>> {
        let mut buf = Vec::new();
        let res = self.read_to_end(&mut buf);
        res.map(|_| buf)
    }

    /// Read all bytes until EOF in this source, returning them as a new buffer.
    ///
    /// See `read_to_string` for other semantics.
    fn read_into_string(&mut self) -> Result<String> {
        let mut buf = String::new();
        let res = self.read_to_string(&mut buf);
        res.map(|_| buf)
    }
}

impl<T> ReadExt for T where T: Read {}

现在我想在一个单独的test/lib.rs文件中为其编写测试。

extern crate readext;

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

#[test]
fn test () {
    let bytes = b"hello";
    let mut input = Cursor::new(bytes);
    let s = input.read_into_string();
    assert_eq!(s, "hello");
}

但Rust一直告诉我

类型std::io::cursor::Cursor<&[u8; 5]>没有实现任何名为read_into_string的方法

我不知道为什么。 显然,我已经使用了use,感到困惑。

1个回答

6
答案已经在错误信息中:

类型 std::io::cursor::Cursor<&[u8; 5]> 没有实现任何名为 read_into_string 的范围方法

问题在于,Cursor<&[u8; 5]>没有实现Read,因为包装的类型是指向固定大小数组而不是切片的指针,因此它也没有实现您的trait。我猜想以下代码应该可以解决问题:
#[test]
fn test () {
    let bytes = b"hello";
    let mut input = Cursor::new(bytes as &[u8]);
    let s = input.read_into_string();
    assert_eq!(s, "hello");
}

这样,输入的类型是Cursor<&[u8]>,它实现了Read,因此也应该实现您的特性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接