Rust:error [E0495]:由于封闭中相互矛盾的要求,无法推断出适当的生命周期以自动引用]

问题描述 投票:1回答:1
原始想法

在我拥有的虚拟项目中,我想使用循环迭代器(例如,生成整数)。

use std::iter::Cycle; type IntegerCycle = Cycle<std::slice::Iter<'static, i32>>; fn generate_cycles() -> [IntegerCycle; 2] { let mut cycles = [ [1, 2].iter().cycle(), [2, 4].iter().cycle(), ]; cycles } fn main() { let mut cycles = generate_cycles(); // ... }

重构

尽管前面的代码按预期工作,但我的实际示例更加复杂,因此我希望调整generate_cycles函数以执行更多操作(在下面的示例中,乘以2,然后生成循环迭代器)。为此,我尝试使用arraymap

extern crate arraymap; use arraymap::ArrayMap; use std::iter::Cycle; type IntegerCycle = Cycle<std::slice::Iter<'static, i32>>; fn generate_cycles() -> [IntegerCycle; 2] { let mut cycles = [ [1, 2], [2, 4], ]; cycles .map(|points| { points.map(|point| point*2) }) .map(|points| { points.iter().cycle() }) } fn main() { let mut cycles = generate_cycles(); // ... }

问题

上述解决方案不起作用,而且,由于Rust初学者最近接触到“生命周期”的概念,我不明白为什么编译器会在这里抱怨,或者我可以做些什么来使他感到高兴。

error[E0495]: cannot infer an appropriate lifetime for autorefdue to conflicting requirements --> src/main.rs:20:14 | 20 | points.iter().cycle() | ^^^^ | note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 19:10... --> src/main.rs:19:10 | 19 | .map(|points| { | __________^ 20 | | points.iter().cycle() 21 | | }) | |_____^ note: ...so that reference does not outlive borrowed content --> src/main.rs:20:7 | 20 | points.iter().cycle() | ^^^^^^ = note: but, the lifetime must be valid for the static lifetime... = note: ...so that the expression is assignable: expected [std::iter::Cycle<std::slice::Iter<'static, i32>>; 2] found [std::iter::Cycle<std::slice::Iter<'_, i32>>; 2]

这里是一个REPL,其中的代码尝试利用arraymaphttps://repl.it/repls/ShadowyStrikingFirm

原始想法在我有一个虚拟项目中,我想使用循环迭代器(例如,生成整数)。使用std :: iter :: Cycle;类型IntegerCycle =周期

&...] >>

rust closures lifetime
1个回答
0
投票
在您的类型声明中:

type IntegerCycle = Cycle<std::slice::Iter<'static, i32>>;

您说您用于构建迭代器的基础切片必须具有'static生存期,也就是说,它们必须永远存在。然后,您使用诸如[1, 2]之类的文字数组作为所有文字,都具有'static'生存期,并且一切顺利:
© www.soinside.com 2019 - 2024. All rights reserved.