我正在学习 Rust,目前正在做练习 here .
到目前为止,我已经想出了以下内容:
impl ParsePosNonzeroError {
...
...
fn from_parseint(err: ParseIntError) -> ParsePosNonzeroError {
ParsePosNonzeroError::ParseInt(err)
}
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)
}
当我这样做时,我收到错误消息:
! 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>`
浏览 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
正在返回 Result<i64, ParsePosNonzeroError>
但你正试图将其影响到 x
,您将其声明为 i64
多变的。您需要添加一个 ?
这样一个Err
将返回结果和 Ok
结果将被展开:let x = s.parse::<i64>().map_err(ParsePosNonzeroError::from_parseint)?;
https://stackoverflow.com/questions/70553721/