"try!" Rust 升级后宏停止工作

"try!" macro stopped working after Rust upgrade

这是一个简单的测试用例,它仍然适用于 playpen:

use std::num;
use std::str::FromStr;
use std::convert::From;

#[derive(Debug)]
struct Error(String);

impl From<num::ParseFloatError> for Error {
    fn from(err: num::ParseFloatError) -> Error {
        Error(format!("{}", err))
    }
}

fn parse(s: &String) -> Result<f64, Error> {
    Ok(try!(<f64 as FromStr>::from_str(&s[..])))
}

fn main() {
    println!("{:?}", parse(&"10.01".to_string()));
}

然而,在我从 git 构建最新的 rustc 之后(现在是 rustc 1.1.0-dev (1114fcd94 2015-04-23)),它停止编译并出现以下错误:

<std macros>:6:1: 6:32 error: the trait `core::convert::From<core::num::ParseFloatError>` is not implemented for the type `Error` [E0277]
<std macros>:6 $ crate:: convert:: From:: from ( err ) ) } } )
               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<std macros>:1:1: 6:48 note: in expansion of try!
exp.rs:15:8: 15:48 note: expansion site
error: aborting due to previous error

我无法找出问题所在。为什么编译器无法找到我的特征实现?

这看起来像是一个错误:std::num::ParseFloatError<f64 as FromStr>::Err 是不同的类型:

impl From<num::ParseFloatError> for Error使用的是后者,而<f64 as FromStr>::from_str(...)返回的是前者。

我打开了 #24748 about it. I also opened #24747 关于改进诊断以使将来更容易调试的内容。

可以通过实现 core::num::ParseFloatError 的特征来解决这个问题。您需要使用 extern crate core; 加载 core 板条箱,并且需要一些功能门。