2015-06-23 24 views
10

什么奇怪的错误:结果没有称为“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` 
+0

尝试'assert_eq!(res1.unwrap(),“只是为了测试”);' – Virbhadrasinh

+1

可能重复[Result类型没有在范围内实现名为''unwrap \']的方法(http://stackoverflow.com/questions/30787271/result-type-does-not-implementation-method-in-scope-named-unwrap) –

回答

15

如果你读了Result::unwrap的文档,你会注意到,这是下一个小部分被称为:

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

这意味着该部分中的方法只存在,只要给定的约束条件是sati sfied。

unwrap不存在的唯一原因是Error未执行Debug

+0

你知道是否有一个针对rustc打开的功能请求来明确列出*为什么当这些方法未被考虑时它找到正确名称的方法?对于通用名称来说,虽然它们可以在一些可能的优先级上并且数量有限,但是这对于C++ SFINAE而言是非常宝贵的,因为Clang引入了这个特性。 –

+1

@MatthieuM。我其实[打开一个回应这个问题](https://github.com/rust-lang/rust/issues/26516)。 –

+0

@DK:现在我不能评论它,你可能想提一下,Clang使用SFINAE排除了C++中的模板方法来管理它,这很类似(因为SFINAE是关于根据某些条件剔除方法的)。这不仅意味着该功能实际上是可实现的,而且还可以为潜在的实施者提供参考实现。 –

相关问题