我正在尝试根据功能的Option输入来切换行为。这个想法是基于给定Option是否存在进行迭代。这是一个最小的(如果很愚蠢的)示例:
use std::iter;
fn main() {
let x: Option<i64> = None;
// Repeat x 5 times if present, otherwise count from 1 to 5
for i in match x {
None => 1..5,
Some(x) => iter::repeat(x).take(5),
} {
println!("{}", i);
}
}
我收到一个错误:
error[E0308]: match arms have incompatible types
--> src/main.rs:7:14
|
7 | for i in match x {
| ______________^
8 | | None => 1..5,
9 | | Some(x) => iter::repeat(x).take(5),
| | ----------------------- match arm with an incompatible type
10 | | } {
| |_____^ expected struct `std::ops::Range`, found struct `std::iter::Take`
|
= note: expected type `std::ops::Range<{integer}>`
found type `std::iter::Take<std::iter::Repeat<i64>>`
当然,这完全有道理,但是我真的很想根据条件选择迭代器,因为for循环中的代码很简单,而复制粘贴所有这些只是为了更改迭代器选择就相当了丑陋且难以维护。
我尝试as Iterator<Item = i64>两臂同时使用,但是这给我带来了有关未定型类型的错误,因为它是一个特征对象。有一个简单的方法可以解决这个问题吗?
我可以使用,.collect()因为它们返回相同的类型并遍历该向量。这是一个很好的快速解决方案,但对于大型列表而言似乎有点多余。
慕虎7371278
潇湘沐
波斯汪