我正在尝试将字符串解析为整数,并在?返回的函数内部传播解析错误Result<_, Box<dyn std::error::Error>>。但是,编译器似乎无法将 a 转换ParseIntError为必要的Box<dyn std::error::Error>:
let res: Result<u32, Box<dyn std::error::Error>> = "0".parse::<u32>();
--------------------------------------- ^^^^^^^^^^^^^^^^^^ expected struct `Box`, found struct `ParseIntError`
expected enum `std::result::Result<_, Box<dyn std::error::Error>>`
found enum `std::result::Result<_, ParseIntError>`
Run Code Online (Sandbox Code Playgroud)
但是,我相信这应该有效,因为:
std::error::Error可以Box<dyn std::error::Error>使用以下方法转换为 a: https: //doc.rust-lang.org/stable/std/boxed/struct.Box.html#impl-From%3CE%3Estd::num::ParseIntError可以转换为 anstd::error::Error因为它Error会自动实现Debug + DisplayParseIntError我缺少什么?
但是,编译器似乎无法将 a 转换
ParseIntError为必要的Box<dyn std::error::Error>:
Rust 不会自动进行这种转换。您的https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#impl-From%3CE%3E链接是正确的,但代码中的任何内容都不会导致该函数运行。
此代码需要使用.map_err(|e| e.into());或.map_err(From::from);映射ParseIntError到您的目标Box<dyn std::error::Error>类型。例如
let res: Result<u32, Box<dyn std::error::Error>> = "0".parse::<u32>().map_err(|e| e.into());
Run Code Online (Sandbox Code Playgroud)
除少数情况外,Rust 通常不会隐式转换值的类型。例如,如果您要使用返回 的函数Result<u32, Box<dyn std::error::Error>>,那么"0".parse::<u32>()?(请注意末尾的问号)将自动使用From::from。