On 2013-05-18, at 17:46 , Renato Lenzi wrote:
> I don't understand why this code is bad:
>
> let n1 = int::from_str(line);
> if n1 == 0
>
> compiler complains:
>
> 00003.rs:7:12: 7:13 error: mismatched types: expected
> `core::option::Option<int>
> ` but found `<VI0>` (expected enum core::option::Option but found integral
> varia
> ble)
> 00003.rs:7 if n1 == 0
>
> wht's wrong?
from_str can fail (if your line is "frubnutz" for instance, there's no
integer making sense) so as the compiler's message explains it returns
an Option<int> (which means "there may or may not be an int here")
rather than an int.
You have to handle this case, Corey Richardson showed how to match[0],
there are a few other options:
* You can use option::map to transform the integer if one parsed
and ignore a failure (option::map will let a None pass through)
* You can use option::get_or_default to either get the parsed integer or
get a default value of some sort if the parsing failed (there's
a special option::get_or_zero which will return `0` in that case)
* For testing things/screwing around, you can also use option::get
which will blow up (error out and terminate the program[1]) if the
parsing failed and you got a None.
see below for demonstration of these (except for map)
[0] depending on the situation you could also do something like:
match int::from_str(line) {
Some(0) => // parsed integer 0
Some(n) => // parsed non-0 integer
None => // not an integer at all
}
if you want to handle an enumerated set of values specially
[1] unless you catch the error of course
fn main() {
let ok = int::from_str("42");
let nok = int::from_str("foo");
// invoke check with a valid parse, Some(42)
check(ok);
// invoke check with an invalid parse, None
check(nok);
}
fn check(val: Option<int>) {
match val {
Some(0) => println("zero"),
Some(x) => println(int::to_str(x)),
None => println("nothing")
}
println(int::to_str(val.get_or_default(-1)));
println(int::to_str(val.get_or_zero()));
println(int::to_str(val.get()));
}
result:
42
42
42
42
nothing
-1
0
rust: task failed at 'option::get none', rust-0.6/src/libcore/option.rs:324
rust: domain main @0x100826810 root task failed
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev