【问题标题】:Referring to matched value in Rust在 Rust 中引用匹配值
【发布时间】:2017-04-19 02:51:32
【问题描述】:

假设我有这个代码:

fn non_zero_rand() -> i32 {
    let x = rand();
    match x {
        0 => 1,
        _ => x,
    }
}

有没有一种简洁的方法将rand() 放入匹配中,然后将其绑定到一个值。例如。像这样:

fn non_zero_rand() -> i32 {
    match let x = rand() {
        0 => 1,
        _ => x,
    }
}

或许:

fn non_zero_rand() -> i32 {
    match rand() {
        0 => 1,
        _x => _x,
    }
}

【问题讨论】:

  • 你的第二个例子应该可以工作
  • _x => _x工作,但它在语义上不正确。前导下划线表示“此值未使用”,因此此处不合适。

标签: rust match


【解决方案1】:

仅由标识符组成的匹配臂将匹配任何值,声明一个名为标识符的变量,并将值移动到变量中。例如:

match rand() {
    0 => 1,
    x => x * 2,
}

创建变量并匹配它的更通用方法是使用@ 模式:

match rand() {
    0 => 1,
    x @ _ => x * 2,
}

在这种情况下,它不是必需的,但在处理条件匹配(例如范围)时会很有用:

match code {
    None => Empty,
    Some(ascii @ 0 ... 127) => Ascii(ascii as u8),
    Some(latin1 @ 160 ... 255) => Latin1(latin1 as u8),
    _ => Invalid
}

【讨论】:

  • x 和未绑定的值是一回事,所以你应该可以使用x => x?
  • @Lee 好点。我已经扩展了答案以显示@ 模式的更实际用法。
【解决方案2】:

您可以将模式绑定到名称:

fn non_zero_rand() -> i32 {
    match rand() {
        0 => 1, // 0 is a refutable pattern so it only matches when it fits.
        x => x, // the pattern is x here,
                // which is non refutable, so it matches on everything
                // which wasn't matched already before
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多