Result has no method called “unwrap()”?

2019-02-16 12:24发布

What a strange error:

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
}

The error is:

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条回答
放荡不羁爱自由
2楼-- · 2019-02-16 12:30

If you read the documentation for Result::unwrap, you'll note that it's under a little section called:

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

This means the methods in that section only exist so long as the given constraints are satisfied.

The only reason unwrap wouldn't exist is that Error doesn't implement Debug.

查看更多
登录 后发表回答