我有一个字符串,我想判断它是分号、逗号还是冒号.如果不是这些,我什么都不想做:

match token.as_ref() {
    ";" => semicolons += 1,
    "," => commas += 1,
    ":" => colons += 1,
     _ => println!(""),
}

这是可行的,但我真的不想打印一堆空行(因为很多令牌不符合这些条件).

解决这个问题最正确的方法是什么?

推荐答案

let some_u8_value = 0u8;
match some_u8_value {
    1 => println!("one"),
    3 => println!("three"),
    5 => println!("five"),
    7 => println!("seven"),
    _ => (),
}

The () is just the unit value, so nothing will happen in the _ case. As a result, we can say that we want to do nothing for all the possible values that we don’t list before the _ placeholder.

也可以使用空块表达式{}.

Rust相关问答推荐

将已知大小的切片合并成一个数组,

关联类型(类型参数)命名约定

trait声明中的生命周期参数

从特征实现调用函数的Rust惯用方法

当rust中不存在文件或目录时,std::FS::File::Create().unwire()会抛出错误

返回的future 不是`发送`

如何删除Mac Tauri上的停靠图标?

定义只有一些字段可以缺省的 struct

考虑到Rust不允许多个可变引用,类似PyTorch的自动区分如何在Rust中工作?

在使用粗粒度锁访问的数据 struct 中使用 RefCell 是否安全?

为什么编译器看不到这个 `From` impl?

Rust 重写函数参数

为什么 js_sys Promise::new 需要 FnMut?

Rust 中指向自身的引用如何工作?

打印 `format_args!` 时borrow 时临时值丢失

Rust/Serde/HTTP:序列化`Option`

无法理解 Rust 对临时值的不可变和可变引用是如何被删除的

如何连接 Rust 中的相邻切片

具有生命周期和以后引用的可变方法

如何在 nom 中构建负前瞻解析器?