假设我有这个代码:
fn non_zero_rand() -> i32 {
let x = rand();
match x {
0 => 1,
_ => x,
}
}
Run Code Online (Sandbox Code Playgroud)
是否有简洁的方法将rand()
匹配,然后将其绑定到一个值.像这样的事情:
fn non_zero_rand() -> i32 {
match let x = rand() {
0 => 1,
_ => x,
}
}
Run Code Online (Sandbox Code Playgroud)
或者可能:
fn non_zero_rand() -> i32 {
match rand() {
0 => 1,
_x => _x,
}
}
Run Code Online (Sandbox Code Playgroud)
use*_*342 14
一个简单的变量将匹配所有值并引入新变量,例如:
match rand() {
0 => 1,
x => x * 2,
}
Run Code Online (Sandbox Code Playgroud)
创建变量并匹配它的更通用的方法是使用@
模式:
match rand() {
0 => 1,
x @ _ => x * 2,
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,没有必要,但在处理范围时它可能会很有用:
match code {
None => Empty,
Some(ascii @ 0 ... 127) => Ascii(ascii as u8),
Some(latin1 @ 160 ... 255) => Latin1(latin1 as u8),
_ => Invalid
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1329 次 |
最近记录: |