问题 结果没有名为“unwrap()”的方法?


多么奇怪的错误:

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`

857
2018-06-23 05:02


起源

尝试 assert_eq!(res1.unwrap(),"just for test"); - Virbhadrasinh
可能重复 结果类型未在名为`unwrap`的作用域中实现方法 - oli_obk


答案:


如果您阅读了文档 Result::unwrap,你会注意到它在一个叫做的小部分之下:

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

这意味着该部分中的方法 只存在 只要给定的约束条件得到满足。

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


14
2018-06-23 05:12



你知道是否有针对rustc打开的功能请求明确列出 为什么 当找到具有正确名称的方法时,不考虑这些方法?对于普通名称来说,它可能很难,虽然它们可以在某些可能的情况下被优先考虑并且数量有限,但是这是我在C ++ SFINAE中发现的非常宝贵的事情,因为Clang引入了该功能。 - Matthieu M.
@MatthieuM。其实我 打开一个回答这个问题。 - DK.
@DK:我现在不能对它发表评论,你可能想提一下Clang用C ++中的模板方法排除SFINAE,这非常相似(因为SFINAE是根据某些条件剔除方法)。这不仅意味着该功能实际上是可实现的,而且还可以为潜在的实现者提供参考实现。 - Matthieu M.