rust - 如何返回反向迭代器?

标签 rust

我正在编写一些代码,我想在其中使用迭代器,或者它的反向版本取决于标志,但是简单的代码给出了错误

pub fn eggs<I,T>(iter:I)->Box<dyn Iterator<Item=T>>
where I:Iterator<Item=T>+DoubleEndedIterator
{
    Box::new(iter.rev())
}

pub fn bacon<I,T>(iter:I, reverse:bool) -> Box<dyn Iterator<Item=T>>
    where I:Iterator<Item=T>+DoubleEndedIterator
{
    if reverse {
        Box::new(iter.rev())
    } else {
        Box::new(iter)
    }

}

fn main()
{
    let pants:String = "pants".into();
    eggs(pants.chars());
}
无法编译:
error[E0310]: the parameter type `I` may not live long enough
 --> src/main.rs:5:5
  |
2 | pub fn eggs<I,T>(iter:I)->Box<dyn Iterator<Item=T>>
  |             - help: consider adding an explicit lifetime bound...: `I: 'static`
...
5 |     Box::new(iter.rev())
  |     ^^^^^^^^^^^^^^^^^^^^ ...so that the type `Rev<I>` will meet its required lifetime bounds
由于我对 Rust 的了解有限,我不确定这些生命周期的界限从何而来。 Iterator上没有特质,或 Rev struct,并且正在移动参数。
鉴于 'static,声明这些类型的函数的正确方法是什么?不是一个真正的选择。
rust playground

最佳答案

这与 .rev() 无关完全没有,但返回 Box<dyn Iterator> :

// error[E0310]: the parameter type `I` may not live long enough
fn boxed_iter<I, T>(iter: I) -> Box<dyn Iterator<Item = T>>
//            - help: consider adding an explicit lifetime bound...: `I: 'static`
where
    I: Iterator<Item = T>,
{
    Box::new(iter)
//  ^^^^^^^^^^^^^^ ...so that the type `I` will meet its required lifetime bounds
}
这样做的原因是像 Box<dyn Trait> 这样的 trait 对象有一个隐含的 'static如果未指定,则生命周期。因此,当编译器尝试强制转换 Box<I> 时至 Box<dyn Iterator> , 如果 I 失败是不是也有'static生命周期。 (如果特征本身包含生命周期,则有一些更具体的规则;您可以更详细地阅读这些规则 here 。)
如果您想要更短的生命周期,则需要将其明确指定为 Box<dyn 'a + Trait> .例如:
fn boxed_iter<'a, I, T>(iter: I) -> Box<dyn 'a + Iterator<Item = T>>
where
    I: 'a + Iterator<Item = T>,
{
    Box::new(iter)
}

关于rust - 如何返回反向迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68091862/

相关文章:

linux - 在 Mac OSX 上交叉编译到 x86_64-unknown-linux-gnu 失败

rust - 无法运行 `time v0.1.25` 的自定义构建命令

string - 如何更新字符串中的字符?

rust - 在 Rust 中多次使用具有相同变量名的 let 关键字

struct - 如何为包含引用的结构实现 AsRef

rust - Option::map 的结果不够长

arrays - 如何从函数返回固定大小的字符串文字数组?

file - 如何写入大于 2 GB 的文件?

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

接受 HashMap 和 BtreeMap 的 Rust 函数