我正在尝试根据函数的 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>
,但这会导致��个关于未定大小类型的错误,因为它是一个trait对象。有没有简单的方法解决这个问题?
当然,我可以使用.collect()
,然后迭代该向量,因为它们返回相同的类型。 这是一个不错的快速修复方法,但对于大型列表来说似乎有点过度了。
Either<Either<A, B>, C>
等类型的对象。 - ShepmasterBox<dyn Iterator>
的解决方案可以。 - undefined