在Rust中引用匹配值 [英] Referring to matched value in Rust
本文介绍了在Rust中引用匹配值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下代码:
fn non_zero_rand() -> i32 {
let x = rand();
match x {
0 => 1,
_ => x,
}
}
是否有一种简便的方法将rand()
放入比赛中,然后将其绑定到一个值.例如.像这样的东西:
Is there a concise way to put the rand()
in the match, and then bind it to a value. E.g. something like this:
fn non_zero_rand() -> i32 {
match let x = rand() {
0 => 1,
_ => x,
}
}
或者:
fn non_zero_rand() -> i32 {
match rand() {
0 => 1,
_x => _x,
}
}
推荐答案
一个简单的变量将匹配所有值并引入新变量,例如:
A simple variable will match all values and introduce the new variable, e.g.:
match rand() {
0 => 1,
x => x * 2,
}
使用@
模式创建和匹配变量的更通用的方法:
A more general way to create a variable and match it is using the @
pattern:
match rand() {
0 => 1,
x @ _ => x * 2,
}
在这种情况下,这不是必需的,但是在处理范围时会很有用:
In this case it is not necessary, but it can come useful when dealing with ranges:
match code {
None => Empty,
Some(ascii @ 0 ... 127) => Ascii(ascii as u8),
Some(latin1 @ 160 ... 255) => Latin1(latin1 as u8),
_ => Invalid
}
这篇关于在Rust中引用匹配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文