gpt4 book ai didi

rust - 结果失败返回 `map_err`

转载 作者:行者123 更新时间:2023-12-03 11:40:32 24 4
gpt4 key购买 nike

我正在弄清楚为什么在返回 map_err 时以下失败:

Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
--> src/main.rs:37:5
|
36 | fn R() -> Result<i32, MyError> {
| -------------------- expected `std::result::Result<i32, MyError>` because of return type
37 | decode().map_err(|e| Err(MyError {v: "changed".to_string() }))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `MyError`, found enum `std::result::Result`
|
= note: expected enum `std::result::Result<_, MyError>`
found enum `std::result::Result<_, std::result::Result<_, MyError>>`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground`.

如果我使用 match 并手动映射它,它就可以工作。

代码:

use std::error::Error;
use std::fmt;
use std::fmt::Display;

#[derive(Debug)]
struct MyError {
v: String,
}

impl MyError {
fn new() -> MyError {
MyError {
v: "oh no!".to_string()
}
}

fn change_message(&mut self, new_message: &str) {
self.v = new_message.to_string();
}
}

impl Error for MyError {}

impl Display for MyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "MyError: {}", &self.v)
}
}

fn decode() -> Result<i32, MyError> {
Err(
MyError::new()
)
}

fn R() -> Result<i32, MyError> {
decode().map_err(|e| Err(MyError {v: "changed".to_string() }))
}

fn main() {
let d = R();
match d {
Ok(t) => println!("t {}", t),
Err(e) => println!("e {}", e)
}
}

最佳答案

如果您查看 signature for map_err您会看到它需要一个接受错误类型并返回错误类型而不是Result的闭包。

decode().map_err(|e| MyError {v: "changed".to_string() })

关于rust - 结果失败返回 `map_err`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64243622/

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