【发布时间】:2015-07-24 05:29:03
【问题描述】:
假设我有以下,
use std::io;
use std::io::Read;
#[derive(Debug)]
enum FooReadError {
UnexpectedEof,
IoError(io::Error),
}
impl From<io::Error> for FooReadError {
fn from(err: io::Error) -> FooReadError {
FooReadError::IoError(err)
}
}
fn read_n_bytes_to_vector<R: Read>(reader: &mut R, length: usize)
-> Result<Vec<u8>, FooReadError> {
let mut bytes = Vec::<u8>::with_capacity(length);
unsafe { bytes.set_len(length); }
let bytes_read = try!(reader.read(&mut bytes[..]));
if bytes_read != length {
Err(FooReadError::UnexpectedEof)
} else {
Ok(bytes)
}
}
fn do_some_read(reader: &mut Read) -> Vec<u8> {
read_n_bytes_to_vector(reader, 16).unwrap()
}
fn main() {
let v = vec![0, 1, 2, 3, 4, 5];
let mut cur = io::Cursor::<Vec<u8>>::new(v);
do_some_read(&mut cur);
}
read_n_bytes_to_vector 应该获取任何实现 trait io::Read 的东西,从中读取 length 字节,并将它们放入一个向量中并返回该向量。
函数do_some_read 有一个io::Read 特征对象。那么,为什么呢:
% rustc ./vec_read.rs
./vec_read.rs:29:5: 29:27 error: the trait `core::marker::Sized` is not implemented for the type `std::io::Read` [E0277]
./vec_read.rs:29 read_n_bytes_to_vector(reader, 16).unwrap()
^~~~~~~~~~~~~~~~~~~~~~
./vec_read.rs:29:5: 29:27 note: `std::io::Read` does not have a constant size known at compile-time
./vec_read.rs:29 read_n_bytes_to_vector(reader, 16).unwrap()
^~~~~~~~~~~~~~~~~~~~~~
我同意 io::Read 不可能实现 Sized 的编译器;但我正在传递一个特征 object ——它们是恒定大小的,所以在这里应该没问题; **那么为什么会出现错误?* 但是等等,为什么它甚至很重要?该函数没有将 io::Read 用于 arg(对吗?),它也采用 trait 对象,因为 arg 是通用的,并且应该采用传入的完整类型。
【问题讨论】: