我正在学习 Rust,它看起来很有趣。我对“匹配”还不是很熟悉,但它看起来相当完整。我使用以下代码(如下)将 String 转换为 i64,其中包含注释掉的行“None”代替下一行“_”。我想知道如果没有下划线的不匹配会发生什么,或者“无”是否可以包罗万象。调用代码需要一个正的 i64,因此负数会导致无效输入(在本例中)。除了可能使用结构之外,我不确定是否可以使用此示例在返回中指示错误。
没有下划线作为匹配项,“None”是否会全部捕获,是否可以用它代替下划线?
是否可以在不使用结构作为返回值的情况下在这样的函数中返回错误?
一般来说,是否可以使用“match”进行不匹配,如果可以,会发生什么情况?
在下面的例子中,使用下划线和使用“None”有什么区别吗?
示例代码:
fn fParseI64(sVal: &str) -> i64 {
match from_str::<i64>(sVal) {
Some(iVal) => iVal,
// None => -1
_ => -1
}
}
最佳答案
- Without underscore as a match item, will "None" catch all, and can it be used instead of underscore?
在这种情况下,是的。 Option<T>
只有2个案例: Some<T>
或 None
.
您已经在匹配 Some
所有值的大小写,None
是唯一剩下的情况,所以
None
将与 _
完全相同.
2. Is it possible to return an error in a function like this without using a struct as the return value?
我建议您阅读这份详细指南以了解处理错误的所有可能方法 - http://static.rust-lang.org/doc/master/tutorial-conditions.html
使用选项和结果将要求您返回一个结构。
3. In general, is it possible for a non-match using "match" and if so, what happens?
Rust 不会编译 match
如果不能保证处理所有可能的情况。你需要有一个 _
如果您没有匹配所有可能性,则从句。
4. In the example below, is there any difference between using underscore and using "None"?
没有。请参阅答案 #1。
以下是编写函数的多种方式中的 3 种:
// Returns -1 on wrong input.
fn alt_1(s: &str) -> i64 {
match from_str::<i64>(s) {
Some(i) => if i >= 0 {
i
} else {
-1
},
None => -1
}
}
// Returns None on invalid input.
fn alt_2(s: &str) -> Option<i64> {
match from_str::<i64>(s) {
Some(i) => if i >= 0 {
Some(i)
} else {
None
},
None => None
}
}
// Returns a nice message describing the problem with the input, if any.
fn alt_3(s: &str) -> Result<i64, ~str> {
match from_str::<i64>(s) {
Some(i) => if i >= 0 {
Ok(i)
} else {
Err(~"It's less than 0!")
},
None => Err(~"It's not even a valid integer!")
}
}
fn main() {
println!("{:?}", alt_1("123"));
println!("{:?}", alt_1("-123"));
println!("{:?}", alt_1("abc"));
println!("{:?}", alt_2("123"));
println!("{:?}", alt_2("-123"));
println!("{:?}", alt_2("abc"));
println!("{:?}", alt_3("123"));
println!("{:?}", alt_3("-123"));
println!("{:?}", alt_3("abc"));
}
输出:
123i64
-1i64
-1i64
Some(123i64)
None
None
Ok(123i64)
Err(~"It's less than 0!")
Err(~"It's not even a valid integer!")
关于rust - 如果没有匹配项,在 Rust 中使用 "match"会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19604985/