【发布时间】:2021-04-22 01:41:17
【问题描述】:
我正在尝试将字符串解析为整数,并在返回 Result<_, Box<dyn std::error::Error>> 的函数中使用 ? 向上传播解析错误。但是,编译器似乎无法将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>`
但是,我相信这应该可行,因为:
-
std::error::Error可以转换为Box<dyn std::error::Error>,使用:https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#impl-From%3CE%3E -
std::num::ParseIntError可以转换为std::error::Error,因为Error自动在Debug + Display上实现,ParseIntError实现了两者
我错过了什么?
【问题讨论】:
标签: rust