lea*_*arn 4 error-handling rust
我正在学习 Rust,目前正在练习我正在学习 Rust,目前正在这里。
到目前为止,我已经提出以下几点:
impl ParsePosNonzeroError {
...
...
fn from_parseint(err: ParseIntError) -> ParsePosNonzeroError {
ParsePosNonzeroError::ParseInt(err)
}
Run Code Online (Sandbox Code Playgroud)
fn parse_pos_nonzero(s: &str)
-> Result<PositiveNonzeroInteger, ParsePosNonzeroError>
{
let x: i64 = s.parse::<i64>().map_err(ParsePosNonzeroError::from_parseint);
PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation)
}
Run Code Online (Sandbox Code Playgroud)
当我这样做时,我收到错误消息:
! Compiling of exercises/error_handling/errors6.rs failed! Please try again. Here's the output:
error[E0308]: mismatched types
--> exercises/error_handling/errors6.rs:34:18
|
34 | let x: i64 = s.parse::<i64>()
| ____________---___^
| | |
| | expected due to this
35 | | .map_err(ParsePosNonzeroError::from_parseint);
| |_____________________________________________________^ expected `i64`, found enum `Result`
|
= note: expected type `i64`
found enum `Result<i64, ParsePosNonzeroError>`
Run Code Online (Sandbox Code Playgroud)
浏览以下文档map_err我看到以下内容:
Maps a Result<T, E> to Result<T, F> by applying a function to a contained Err value, leaving an Ok value untouched.
我缺少什么?为什么这不起作用?
map_err正在返回 aResult<i64, ParsePosNonzeroError>但您试图将其影响到x您声明为i64变量的 。您需要添加 a?以便Err返回结果并Ok解包结果:let x = s.parse::<i64>().map_err(ParsePosNonzeroError::from_parseint)?;