首页 > 解决方案 > Rust 匹配模式:为特定情况绑定文字值

问题描述

我确实有以下比赛声明

match it.peek() {
     Some('0') | Some('1') | Some('2') | Some('3')
   | Some('4') | Some('5') | Some('6') | Some('7')
   | Some('8') | Some('9') => { list.push(...) }
     _ => {...}
}

现在我想写一个简单地获取Some案例中的元素,我确定这不会起作用,但你会从中得到想法:

match it.peek() {
     Some('0' as digit) | Some('1' as digit) | Some('2' as digit) | Some('3' as digit)
   | Some('4' as digit) | Some('5' as digit) | Some('6' as digit) | Some('7'  as digit)
   | Some('8' as digit) | Some('9' as digit) => { list.push(digit) }
     _ => {...}
}

这可能吗?我知道我可以嵌套第二个匹配,从数字中解包字符,但是我需要_两次实现这种情况,我想避免这种情况。

标签: rust

解决方案


您可以使用条件匹配char::is_digit

fn main() {
    let c = Some('2');
    match c {
        Some(c) if c.is_digit(10) => println!("Found a digit: {}", c),
        _ => println!("Found another thing"),
    }
}

推荐阅读