我只是想将输入的字符串转换为整数。我知道这可以通过将 unwrap
应用于 from_str
来完成,但我想我会尝试正确处理错误情况并使用匹配项提取值。它没有按预期工作,而是出现此错误...
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"),
}
}
我错过了什么?
最佳答案
我们来看the definition of from_str
:
pub fn from_str<A: FromStr>(s: &str) -> Option<A>
返回类型,你看,可能是 Option
任何实现 FromStr
的类型,例如 int
, u8
和 IpAddr
.如果你不明确说出什么A
是,通过改变 from_str(…)
至 from_str::<int>(…)
或类似的,编译器将尝试弄清楚它可能是什么。在这种情况下,它将向前看并看到x
。类型为 A
并基于 x
的用法, 它必须实现 std::fmt::Show
以及。它无法推断出任何其他内容。
那么,什么类型同时实现了 FromStr
和 Show
?它们有很多,一旦超过一个,编译器就不可能确定你的意思,所以它会放弃。
解决方案是通过编写 from_str::<int>(num.as_slice())
来规定您希望将该参数解析为什么类型。或类似的。
关于rust - 从具有匹配项的选项中提取值会出现 "unable to infer enough type information..."错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27310017/