I'm trying simply to convert an inputted string into an integer. I know this can be done by applying unwrap
to from_str
but I figured I'd try to handle the error case properly and extract the value with a match instead. Instead of it working as expected I just get this error...
error: unable to infer enough type information about
_
; type annotations requiredwhich points to the
xin
Some(x)`
fn main () {
let ref num = os::args()[1];
match from_str(num.as_slice()) {
Some(x) => println!("{}", x),
None => println!("string cannot be converted to int"),
}
}
What am I missing?
Let’s look at the definition of from_str
:
pub fn from_str<A: FromStr>(s: &str) -> Option<A>
The return type, you see, may be an Option
of any type that implements FromStr
, such as int
, u8
and IpAddr
. If you don’t say explicitly what A
is, by changing from_str(…)
to from_str::<int>(…)
or similar, the compiler will try to figure out what it can be. In this case, it will look forward and see that x
is of type A
and based on the usage of x
, it must implement std::fmt::Show
as well. There is nothing else that it can infer.
Well then, what types implement both FromStr
and Show
? There are quite a few of them, and as soon as there’s more than one it is impossible for the compiler to decide what you meant, so it gives up.
The solution is to stipulate what type you are wishing to parse that argument as, by writing from_str::<int>(num.as_slice())
or similar.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments