多么奇怪的错误:
use std::collections::BTreeMap;
struct MyStruct1;
struct Error;
fn get_res() -> Result<(MyStruct1, BTreeMap<String, String>), Error> {
Err(Error)
}
fn main() {
let res1 = get_res();
assert!(res1.is_ok());
assert_eq!("just for test", res1.unwrap()); //error
}错误是:
error: no method named `unwrap` found for type `std::result::Result<(MyStruct1, std::collections::BTreeMap<std::string::String, std::string::String>), Error>` in the current scope
--> src/main.rs:13:38
|
13 | assert_eq!("just for test", res1.unwrap()); //error
| ^^^^^^
|
= note: the method `unwrap` exists but the following trait bounds were not satisfied: `Error : std::fmt::Debug`发布于 2015-06-23 05:12:09
如果您阅读了Result::unwrap的文档,您将注意到它在一个名为:
impl<T, E> Result<T, E>
where E: Debug这意味着该部分中的方法只在满足给定的约束条件下才存在。
unwrap不存在的唯一原因是Error没有实现Debug。
发布于 2022-05-29 20:33:19
我知道这个问题由来已久,但我经常在format!(...)不可用的环境中进行嵌入式开发,并认为我可以把它放在这里:
pub trait DiscreetUnwrap<T, E> {
fn duwrp(self) -> T;
}
impl<T, E> DiscreetUnwrap<T, E> for Result<T, E> {
fn duwrp(self) -> T {
match self {
Ok(r) => r,
Err(_) => {
panic!("duwrp() failed.")
},
}
}
}只要在任何地方使用.duwrp()就可以使用.unwrap(),这样就不会再有麻烦了。您显然会丢失实际的错误消息,但是如果可能的话,您可以对代码进行适当的格式化(例如,如果您正在使用ufmt)。
https://stackoverflow.com/questions/30994176
复制相似问题