相关疑难解决方法(0)

有条件地迭代几个可能的迭代器之一

我正在尝试根据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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

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),
   | | …
Run Code Online (Sandbox Code Playgroud)

rust

9
推荐指数
4
解决办法
1407
查看次数

标签 统计

rust ×1