[英]Implementing the From trait for a ParseIntError
When using the try! 使用时试试! macro, it uses the From trait to transform an error into the desired error. 宏,它使用From特性将错误转换为所需的错误。
I would like to transform some errors into my own type. 我想将一些错误转换为我自己的类型。 This goes great for eg io::Error, but I can't get it to work for an error type from core. 这对于io :: Error非常有用,但是我无法从核心将其用于错误类型。
use std::io;
pub struct ParserError {
pub message: String,
}
impl From<io::Error> for ParserError {
fn from(e: io::Error) -> ParserError {
ParserError{message: format!("Generic IO error: {}", e.description())}
}
}
This works well for doing try! 这很适合尝试! on anything io. 在任何东西上。 But now for parsing: 但是现在进行解析:
fn parse_string(s: &str) -> Result<u64, ParserError> {
let i = try!(s.parse::<u64>());
return Ok(i);
}
My error says: 我的错误说:
error: the trait core::convert::From<parser::ParserError>
is not implemented for the type `core::num::ParseIntError 错误:特征类型core::convert::From<parser::ParserError>
未实现,类型为core :: num :: ParseIntError
I tried to implement this From: 我尝试实现此发件人:
impl From<core::num::ParseIntError> for ParserError {
fn from(_: core::num::ParseIntError) -> ParserError {
ParserError{message: "Invalid data type".to_string()}
}
}
But I can't get core imported. 但是我无法导入核心。 How to do this? 这个怎么做?
The modules from core
are reexported by std
. 来自core
的模块由std
。 You can fix your error by just replacing core
by std
in your code: 您可以通过在代码中用std
替换core
来解决错误:
impl From<std::num::ParseIntError> for ParserError {
fn from(_: std::num::ParseIntError) -> ParserError {
ParserError{message: "Invalid data type".to_string()}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.