深化了包裹向量执行IntoIterator
按the Rust book,我也试图实施IntoIterator的参考到包装,按the following code (Playground link)的例子:我是否错误地实现了IntoIterator作为参考,或者这是一个应该报告的Rust错误?
struct VecWrapper(Vec<i32>);
impl VecWrapper {
fn iter(&'static self) -> Iter {
Iter(Box::new(self.0.iter()))
}
}
struct Iter(Box<Iterator<Item = &'static i32>>);
impl Iterator for Iter {
type Item = &'static i32;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
impl IntoIterator for &'static VecWrapper {
type Item = &'static i32;
type IntoIter = Iter;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
fn main() {
// let test = vec![1, 2, 3]; // obviously, works
let test = VecWrapper(vec![1, 2, 3]); // not working
for v in &test {
println!("{}", v);
}
}
虽然实现汇总,尝试在main
使用它不会出现以下错误:
rustc 1.15.0-nightly (43006fcea 2016-11-15)
error: `test` does not live long enough
--> <anon>:31:15
|
31 | for v in &test {
| ^^^^ does not live long enough
...
34 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
此代码是由很多东西我真的想为使用使用简化仅使用'static
生命周期,使用现有的包含类型,并使用i32
作为内部(迭代)类型,但它只能用于解释问题。
Edit_Added:虽然以不使用'static
和使用+ 'a
与性状接受的答案解决问题的第一部分,我还是很具有实际的代码,这是一个LazyList实现的问题。我已经发布,作为separate question。
你应该回滚你的编辑[并提出一个新问题](http://meta.stackoverflow.com/q/253762/155423) - 当然,搜索以确保它不是重复的。 – Shepmaster
@Shepmaster,我按照你的建议做了,[新的问题在这里](http://stackoverflow.com/questions/40687955/am-i-incorrectly-implementing-intoiterator-for-a-reference-to-a- lazylist-impleme)。 – GordonBGood