rust - 如何在 rust 中将迭代器保存在结构中

标签 rust

我正在尝试这样做

struct RwindIter {
    iter: Box<dyn Iterator<Item = String>>,
}

fn build(i: impl Iterator<Item = String>) -> RwindIter {
    RwindIter { iter: Box::new(i) }
}
但是我得到了这个错误
   Compiling myml v0.1.0 (/Users/gecko/code/myml)
error[E0310]: the parameter type `impl Iterator<Item = String>` may not live long enough
  --> src/main.rs:47:23
   |
47 |     RwindIter { iter: Box::new(i) }
   |                       ^^^^^^^^^^^
   |
note: ...so that the type `impl Iterator<Item = String>` will meet its required lifetime bounds
  --> src/main.rs:47:23
   |
47 |     RwindIter { iter: Box::new(i) }
   |                       ^^^^^^^^^^^
help: consider adding an explicit lifetime bound  `'static` to `impl Iterator<Item = String>`...
   |
46 | fn build(i: impl Iterator<Item = String> + 'static) -> RwindIter {
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0310`.
error: could not compile `myml`.

To learn more, run the command again with --verbose.
我原以为Box::new(x)将占用x,因此我无法弄清楚错误消息的含义。有任何想法吗?

更新
好的,我知道impl语法有一些限制。这有效
struct I {}

impl Iterator for I {
    type Item = String;
    fn next(&mut self) -> Option<String> {
        None
    }
}

fn build(i: I) -> RwindIter {
    RwindIter { iter: Box::new(i) }
}

最佳答案

我建议仅使用常规的泛型来解决该问题。

pub struct FooIter<I> {
    iter: I,
}

impl<I> FooIter<I> {
    pub fn new(iter: I) -> Self {
        FooIter { iter }
    }
}

impl<I: Iterator<Item=String>> Iterator for FooIter<I> {
    type Item = String;
    
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }
}
但是,只要您提供了生命周期限制,您仍然可以使用dyn Iterator<Item=String>。但是,这可能会在以后的实现过程中导致大量的生命周期困惑,具体取决于您与该结构的交互方式。
pub struct FooIter<'a> {
    iter: Box<dyn Iterator<Item=String> + 'a>,
}

impl<'a> FooIter<'a> {
    pub fn new(iter: impl Iterator<Item=String> + 'a) -> Self {
        FooIter {
            iter: Box::new(iter),
        }
    }
}

impl<'a> Iterator for FooIter<'a> {
    type Item = String;
    
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }
}

关于rust - 如何在 rust 中将迭代器保存在结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63406233/

相关文章:

multithreading - 使用 channel 在线程之间传递 Rust pnet 数据包

generics - 如何调用像 std::num::Float::epsilon() 这样的静态特征方法?

rust - 如何在 Rust 中编写管道过滤器?

rust - 如果缺少 include_bytes!(…) 目标,则回退到替代值

regex - 在成功/失败之前查找正则表达式在字符串中查看了多少个字符

rust - Rust traits 是否类似于 JavaScript mixin?

rust - 为什么我不能将 &&mut 转换为 && ?

casting - 如何转换我知道是整数的泛型类型?

rust - 当 FnBox 闭包无法放入 Arc 时,如何克隆它?

rust - 什么是非词汇生命周期?