rust - 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) }
_ => {...}
}
这可能吗?我知道我可以嵌套第二个匹配,从数字中解包字符,但是我需要_
两次实现这种情况,我想避免这种情况。
解决方案
您可以使用条件匹配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"),
}
}
推荐阅读
- firebase - 如何在flutter应用程序的firestore数据库中的文档中添加文档ID
- python-3.x - 将 json 对象作为键控消息传递给 apache kafka
- javascript - Vue js根据其ID编辑内容
- java - Ansible 挂起执行 playbook 命令
- python - Python,网页抓取条形图
- json - 如何在 JS 中处理 Trello API 返回的 JSON
- java - Java Stream:如何仅更改流的第一个元素?
- r - 为什么多列在R中显示为一个向量
- java - json模式中的空对象验证
- python - 如何使用 pandas 查找大学排名和全球排名?