7

I'm learning Rust and it looks very interesting. I'm not yet very familiar with "match", but it looks to be fairly integral. I was using the following code (below) to convert String to i64 which included the commented-out line "None" in place of the next line "_". I wondered what happened in the event of a non-match without underscore or whether "None" may be a catch-all. The calling-code requires a positive i64, so negative results in an invalid input (in this case). I'm not sure if it's possible to indicate an error in a return using this example other than perhaps using a struct.

  1. Without underscore as a match item, will "None" catch all, and can it be used instead of underscore?

  2. Is it possible to return an error in a function like this without using a struct as the return value?

  3. In general, is it possible for a non-match using "match" and if so, what happens?

  4. In the example below, is there any difference between using underscore and using "None"?

Example code :

fn fParseI64(sVal: &str) -> i64 {
    match from_str::<i64>(sVal) {
        Some(iVal) => iVal,
//        None => -1
     _ => -1    
    }
}
4

1 回答 1

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

在这种情况下,是的。Option<T>:Some<T>或.只有 2 种情况None。您已经匹配Some所有值的大小写,None是唯一剩下的大小写,因此 None行为与_.

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

我建议您阅读这份详细指南以了解处理错误的所有可能方法 - http://static.rust-lang.org/doc/master/tutorial-conditions.html

使用选项和结果将要求您返回一个结构。

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

match如果不能保证处理所有可能的情况,Rust 将不会编译 a 。_如果您不匹配所有可能性,则需要有一个子句。

 4. 在下面的例子中,使用下划线和使用“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!")
于 2013-10-26T10:02:25.557 回答