【发布时间】:2017-04-01 18:33:05
【问题描述】:
进一步介绍了根据the Rust book 为包装向量实现IntoIterator 的示例,我还尝试根据the following code (Playground link) 实现 IntoIterator 以获取对包装器的引用: p>
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 中使用它的尝试不会出现以下错误:
error[E0597]: `test` does not live long enough
--> src/main.rs:31:14
|
31 | for v in &test {
| ^^^^^
| |
| borrowed value does not live long enough
| argument requires that `test` is borrowed for `'static`
...
34 | }
| - `test` dropped here while still borrowed
与我实际想要使用的代码相比,此代码已大大简化为仅使用 'static 生命周期,使用现有的包含类型,并将 i32 用于内部(迭代)类型,但归结为只显示问题。
接受的答案解决了问题的第一部分,即不使用 'static 和使用带有特征的 + 'a。我仍然对实际代码有问题,这是一个LazyList 实现。我已将其发布为Am I incorrectly implementing IntoIterator for a reference to a LazyList implementation or is this a Rust bug?。
【问题讨论】:
标签: iterator rust lifetime borrow-checker