rust - 从具有匹配项的选项中提取值会出现 "unable to infer enough type information..."错误

标签 rust

我只是想将输入的字符串转换为整数。我知道这可以通过将 unwrap 应用于 from_str 来完成,但我想我会尝试正确处理错误情况并使用匹配项提取值。它没有按预期工作,而是出现此错误...

error: unable to infer enough type information about _; type annotations requiredwhich points to thexinSome(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 , u8IpAddr .如果你不明确说出什么A是,通过改变 from_str(…)from_str::<int>(…)或类似的,编译器将尝试弄清楚它可能是什么。在这种情况下,它将向前看并看到x。类型为 A并基于 x 的用法, 它必须实现 std::fmt::Show 以及。它无法推断出任何其他内容。

那么,什么类型同时实现了 FromStrShow ?它们有很多,一旦超过一个,编译器就不可能确定你的意思,所以它会放弃。

解决方案是通过编写 from_str::<int>(num.as_slice()) 来规定您希望将该参数解析为什么类型。或类似的。

关于rust - 从具有匹配项的选项中提取值会出现 "unable to infer enough type information..."错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27310017/

相关文章:

vector - "std::vec"与 "collections::vec"

rust - 使用部分移动的值 : `*head`

rust - 仅构建 `lib` 目标

rust - 在 Rust 中使用 warp 框架同时在多个端口(http、https)上提供服务

mongodb - 错误 : type parameter `D` must be used as the type parameter for some local type

rust - 在采用 &self 或 &mut self 的函数中进行模式匹配时,如何避免 ref 关键字?

rust - 有没有办法结合多个特征来定义新特征?

rust - 为什么没有为明确实现的类型实现特征?

rust - 如何高效地将可显示项插入字符串?

c - 如何修复 "found Rust tuple type in foreign module; consider using a struct instead"警告