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();
// ...
}
问题
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,其中的代码尝试利用arraymap
:https://repl.it/repls/ShadowyStrikingFirm。
原始想法在我有一个虚拟项目中,我想使用循环迭代器(例如,生成整数)。使用std :: iter :: Cycle;类型IntegerCycle =周期
&...] >>
type IntegerCycle = Cycle<std::slice::Iter<'static, i32>>;
您说您用于构建迭代器的基础切片必须具有'static
生存期,也就是说,它们必须永远存在。然后,您使用诸如[1, 2]
之类的文字数组作为所有文字,都具有'static'
生存期,并且一切顺利: