无法将特征方法纳入范围
Can't bring trait methods into scope
我有这个 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 一直在告诉我
type std::io::cursor::Cursor<&[u8; 5]>
没有在名为 read_into_string
的范围内实现任何方法
我不知道为什么。显然我已经 use
了。困惑。
答案已经在错误中:
type std::io::cursor::Cursor<&[u8; 5]> does not implement any method
in scope named read_into_string
问题是,Cursor<&[u8; 5]>
没有实现 Read
因为包装类型是指向固定大小数组而不是切片的指针,所以它也没有实现你的特征。我想这些方面的东西应该有效:
#[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");
}
这样 input
是实现 Read
的 Cursor<&[u8]>
类型,因此也应该实现你的特征。
我有这个 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 一直在告诉我
type std::io::cursor::Cursor<&[u8; 5]>
没有在名为 read_into_string
我不知道为什么。显然我已经 use
了。困惑。
答案已经在错误中:
type std::io::cursor::Cursor<&[u8; 5]> does not implement any method in scope named read_into_string
问题是,Cursor<&[u8; 5]>
没有实现 Read
因为包装类型是指向固定大小数组而不是切片的指针,所以它也没有实现你的特征。我想这些方面的东西应该有效:
#[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");
}
这样 input
是实现 Read
的 Cursor<&[u8]>
类型,因此也应该实现你的特征。