- Without underlining as a matching element, "None" will catch everything and can it be used instead of underlining?
In this case, yes. For Option<T> only 2 cases: Some<T> or None . You are already matching the Some case for all values, None is the only case that remains, so None will behave exactly like _ .
2. Is it possible to return an error in such a function without using struct as a return value?
I would advise you to read this detailed guide to understand all the possible ways to handle errors - http://static.rust-lang.org/doc/master/tutorial-conditions.html
Using parameters and results will require a structure return.
3. In general, is match possible using match, and if so, what happens?
Rust will not compile match if it cannot guarantee that all possible cases will be handled. You will need to have a suggestion _ if you do not meet all the possibilities.
4. In the example below, is there a difference between using underscores and using No?
No. See Answer No. 1.
Here are three ways you can write your function:
// 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 less than 0!") }, None => Err(~"It 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")); }
Output:
123i64 -1i64 -1i64 Some(123i64) None None Ok(123i64) Err(~"It less than 0!") Err(~"It not even a valid integer!")