为 ParseIntError 实现 From 特性
Implementing the From trait for a ParseIntError
用的时候试试!宏,它使用 From 特性将错误转换为所需的错误。
我想将一些错误转化为我自己的类型。这非常适合例如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())}
}
}
这很适合做尝试!在任何 io 上。但现在解析:
fn parse_string(s: &str) -> Result<u64, ParserError> {
let i = try!(s.parse::<u64>());
return Ok(i);
}
我的错误是:
错误:特性 core::convert::From<parser::ParserError>
没有为类型 `core::num::ParseIntError
实现
我尝试实现这个 来自:
impl From<core::num::ParseIntError> for ParserError {
fn from(_: core::num::ParseIntError) -> ParserError {
ParserError{message: "Invalid data type".to_string()}
}
}
但是我无法导入核心。如何做到这一点?
来自 core
的模块由 std
重新导出。您可以通过在代码中将 core
替换为 std
来修复错误:
impl From<std::num::ParseIntError> for ParserError {
fn from(_: std::num::ParseIntError) -> ParserError {
ParserError{message: "Invalid data type".to_string()}
}
}
用的时候试试!宏,它使用 From 特性将错误转换为所需的错误。
我想将一些错误转化为我自己的类型。这非常适合例如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())}
}
}
这很适合做尝试!在任何 io 上。但现在解析:
fn parse_string(s: &str) -> Result<u64, ParserError> {
let i = try!(s.parse::<u64>());
return Ok(i);
}
我的错误是:
错误:特性 core::convert::From<parser::ParserError>
没有为类型 `core::num::ParseIntError
我尝试实现这个 来自:
impl From<core::num::ParseIntError> for ParserError {
fn from(_: core::num::ParseIntError) -> ParserError {
ParserError{message: "Invalid data type".to_string()}
}
}
但是我无法导入核心。如何做到这一点?
来自 core
的模块由 std
重新导出。您可以通过在代码中将 core
替换为 std
来修复错误:
impl From<std::num::ParseIntError> for ParserError {
fn from(_: std::num::ParseIntError) -> ParserError {
ParserError{message: "Invalid data type".to_string()}
}
}