【问题标题】:Result has no method called "unwrap()"?结果没有名为“unwrap()”的方法?
【发布时间】:2015-09-08 17:51:45
【问题描述】:

多么奇怪的错误:

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`

【问题讨论】:

标签: rust


【解决方案1】:

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

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

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

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

【讨论】:

  • 您知道是否有针对 rustc 打开的功能请求以显式列出 为什么 在找到具有正确名称的方法时未考虑这些方法?对于普通名称来说,这可能很困难,尽管它们可能在某些情况下被优先考虑并且数量有限,但是自从 Clang 引入该功能以来,我发现这是 C++ SFINAE 中无价的东西。
  • @MatthieuM。我其实是opened one in response to this question
  • 知道为什么他们没有为非Debug 类型实现unwrap() 吗?
  • @Timmmm 我认为这是因为他们想在恐慌中包含一些信息性消息!如果您尝试 unwrap() 错误,则会发生这种情况 - 您需要 Debug 将 E 值转换为此消息。
  • 那么如果你想unwrap()但是你没有定义错误类型所以你不知道它是否是Debug,你会怎么做?使用TryInto&lt;usize&gt; 遇到这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多