gpt4 book ai didi

rust - FromStr & FromErr 解析字符串时出现问题

转载 作者:行者123 更新时间:2023-11-29 08:14:49 25 4
gpt4 key购买 nike

我正在尝试编写一个简单的 Rust 函数来解析字符串并创建结构。我正在使用 Result 作为解析结果。我希望它适用于多种数字类型(整数和 float )。我正在使用相同的 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 ,但我不确定我必须实现什么才能使这项工作成功。

最佳答案

这是测试版之前的最后一刻更改之一。 FromError 消失了,您现在应该使用通用的 From 类型:http://doc.rust-lang.org/nightly/std/convert/trait.From.html

关于rust - FromStr & FromErr 解析字符串时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29435792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com