【发布时间】:2020-05-18 15:51:37
【问题描述】:
原始想法
在我的一个虚拟项目中,我想使用循环迭代器(例如生成整数)。
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,代码尝试使用 arraymap: https://repl.it/repls/ShadowyStrikingFirm 。
【问题讨论】: