rust - 结果没有名为 "unwrap()"的方法?

标签 rust

多么奇怪的错误:

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`

最佳答案

如果您阅读 Result::unwrap 的文档,您会注意到它位于一个名为:

impl<T, E> Result<T, E> 
    where E: Debug

这意味着该部分中的方法仅存在,只要满足给定的约束。

unwrap 不存在的唯一原因是 Error 没有实现 Debug

关于rust - 结果没有名为 "unwrap()"的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30994176/

相关文章:

macros - 可以对传递给宏的标识符应用约束吗?

rust - cargo install 是否有等效的更新命令?

rust - 检查目录中是否存在文件夹

rust - 如何从Rust中的函数返回计算出的字符串?

string - str::contains 适用于引用但不适用于实际值

rust - 如何返回可变引用?

rust - BeforeMiddleware 实现需要 core::ops::Fn 实现

rust - 过滤与迭代器中模式匹配的值的惯用方法

rust - 如何一次执行多个异步函数并得到结果?

rust - 是否可以检查 rust 的闭合度是否相等?