rust - 如果没有匹配项,在 Rust 中使用 "match"会发生什么?

标签 rust

我正在学习 Rust,它看起来很有趣。我对“匹配”还不是很熟悉,但它看起来相当完整。我使用以下代码(如下)将 String 转换为 i64,其中包含注释掉的行“None”代替下一行“_”。我想知道如果没有下划线的不匹配会发生什么,或者“无”是否可以包罗万象。调用代码需要一个正的 i64,因此负数会导致无效输入(在本例中)。除了可能使用结构之外,我不确定是否可以使用此示例在返回中指示错误。

  1. 没有下划线作为匹配项,“None”是否会全部捕获,是否可以用它代替下划线?

  2. 是否可以在不使用结构作为返回值的情况下在这样的函数中返回错误?

  3. 一般来说,是否可以使用“match”进行不匹配,如果可以,会发生什么情况?

  4. 在下面的例子中,使用下划线和使用“None”有什么区别吗?

示例代码:

fn fParseI64(sVal: &str) -> i64 {
    match from_str::<i64>(sVal) {
        Some(iVal) => iVal,
//        None => -1
     _ => -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/

相关文章:

rust - 使用git添加rust Cargo中的依赖项时是否可以使用路径

rust - 在单个表达式中创建、初始化和运行的惯用方式

rust - 让编译器相信数组的每个索引都将被初始化

rust - 为什么 HashMap::get_mut() 会在其余范围内取得 map 的所有权?

parallel-processing - 是否可以将 Rayon 和 Faster 结合起来?

rust - 从字符串和 yield 向量中过滤所有非整数

rust - 如何创建具有计时时区的通用 Rust 结构?

rust - 如何迭代分隔字符串,累积先前迭代的状态而不显式跟踪状态?

docker buildx "exec user process caused: exec format error"

Rust 中的嵌套常量