我正在尝试编写一个简单的Rust函数来解析字符串并创建一个struct。我使用Result
来解析结果。我希望它适用于许多数字类型(整数和浮点数)。我使用相同的approach as used in Rust's result documentation,我的错误类型是一条简单的错误消息(&str
)
这是我的源代码:
#![feature(plugin)]
#![plugin(regex_macros)]
extern crate regex;
use std::str::FromStr;
use regex::Regex;
struct Point<T> {
x: T,
y: T
}
fn parse_string<T: FromStr>(input: &str) -> Result<Point<T>, &'static str> {
let input = input.trim();
if input.len() == 0 {
return Err("Empty string");
}
let re = regex!(r"point2d\{ *x=(.*)+, *y=(.*)+ *\}");
let mresult = try!(re.captures(input).ok_or("Could not match regex"));
let x_str = try!(mresult.at(1).ok_or("Couldn't find X"));
let y_str = try!(mresult.at(2).ok_or("Couldn't find Y"));
let x: T = try!(T::from_str(x_str));
let y: T = try!(T::from_str(y_str));
Ok(Point{ x: x, y: y });
}
fn main() {
let point: Point<i64> = parse_string("point2d{x=10, y=20}").unwrap();
}
编译错误:
Compiling fromerrtest v0.0.1 (file:///XXXXXX)
<std macros>:6:1: 6:41 error: the trait `core::error::FromError<<T as core::str::FromStr>::Err>` is not implemented for the type `&str` [E0277]
<std macros>:6 $ crate:: error:: FromError:: from_error ( err ) ) } } )
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<std macros>:1:1: 6:57 note: in expansion of try!
src/main.rs:22:16: 22:41 note: expansion site
<std macros>:6:1: 6:41 error: the trait `core::error::FromError<<T as core::str::FromStr>::Err>` is not implemented for the type `&str` [E0277]
<std macros>:6 $ crate:: error:: FromError:: from_error ( err ) ) } } )
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<std macros>:1:1: 6:57 note: in expansion of try!
src/main.rs:23:16: 23:41 note: expansion site
error: aborting due to 2 previous errors
Could not compile `fromerrtest`.
我已阅读Armin Ronacher's explaination of FromErr,但我不确定我必须实施哪些方法才能使其发挥作用。
答案 0 :(得分:3)
这是beta之前的最后一分钟变化之一。 FromError
已消失,您现在应使用常规From
类型:http://doc.rust-lang.org/nightly/std/convert/trait.From.html