我正在尝试编写一个库,该库将读取字节(例如从文件中),并解析出对象并返回一个交互器。但是,即使使用虚拟版本,我也在实现迭代器时遇到问题。
这是我的代码:
use std::io::Read;
// One of the objects I want to return
pub struct ObjA {
data: i8,
}
// There might be other kinds of objects here.
pub enum MyObj {
ObjA(ObjA),
}
// There will be other input formats, and I want a generic trait for "read bytes and return MyObj's"
pub trait ObjReader<R> {
// This should create the parser/reader from a std::io::Read source
fn new(R) -> Self;
// This will iterate over the objects. (AFAIK this is how to return an iterator)
fn objects(&self) -> Box<Iterator<Item=MyObj>>;
}
// The data will be in XML, so here's a stupid struct that will (eventually) parse it and return objects. It obv. takes a `Read`
pub struct XMLReader<R: Read> {
inner_reader: R,
}
// The XMLReader will be an ObjReader
impl<R: Read> ObjReader<R> for XMLReader<R> {
fn new(reader: R) -> XMLReader<R> {
XMLReader { inner_reader: reader }
}
// Return the iterator for the objects, I'll keep it simple and iterate over itself, rather than create a new struct
fn objects(&self) -> Box<Iterator<Item=MyObj>> {
Box::new(self)
}
}
// Make XMLReader be an iterator
impl<R: Read> Iterator for XMLReader<R> {
type Item = MyObj;
// Right now, it's always empty. This is a stub
fn next(&mut self) -> Option<Self::Item> {
None
}
}
// Dummy main to allow it to compile
fn main() {
}
我收到此错误:
$ multirust run beta rustc test.rs
test.rs:24:13: 24:27 error: the trait `core::iter::Iterator` is not implemented for the type `&XMLReader<R>` [E0277]
test.rs:24 Box::new(self)
^~~~~~~~~~~~~~
test.rs:24:13: 24:27 help: run `rustc --explain E0277` to see a detailed explanation
test.rs:24:13: 24:27 note: `&XMLReader<R>` is not an iterator; maybe try calling `.iter()` or a similar method
test.rs:24:13: 24:27 note: required for the cast to the object type `core::iter::Iterator<Item=MyObj> + 'static`
error: aborting due to previous error
错误在于XMLReader
如何不迭代,但我已经为它安装了迭代器。我怎样才能做到这一点?
我正在使用来自多锈的 rust 1.7 测试版。(稳定的锈格在我身上断了...
$ multirust run beta rustc --version
rustc 1.7.0-beta.4 (5ed7d4e31 2016-02-26)
答案既简单又烦人:您已经实现了XMLReader<R>
而不是&XMLReader<R>
的Iterator
,或者您必须Box
值而不是引用。
前者不会让你走得更远,因为那样你就会尝试围绕引用创建一个Box
......有两种可能性:
- 为读取器和迭代器提供不同的类型
- 更改
objects
的签名以按值获取self
然后,您还必须注意约束R
以确保它不会引用在您完成迭代之前可能停止存在的对象。'static
绑定将更容易开始。