Trouble with FromStr & FromErr to parse a string
我正在尝试编写一个简单的Rust函数来解析字符串并创建结构。 我正在使用
这是我的源代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #![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(); } |
和编译器错误:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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对FromErr的解释,但是我不确定要实现此功能必须实现什么。
这是Beta之前的最后一分钟更改。