Result type does not implement method in scope named `unwrap`

For some reason, the Rust compiler is complaining that Result doesn't implement unwrap , even though the Error type I provided does implement Debug. The code that's error-ing is provided below.

use std::fmt::{Display, Debug};
use std::error::Error;

trait MyError: Error + Display + Debug {}
type MyResult<T> = Result<T, MyError>;

trait Foo: Clone {}

trait MyTrait {
    fn my_function<T: Foo>(&self) -> MyResult<T>;

    fn unwrap_function<T: Foo>(&self) -> T {
        self.my_function().unwrap()
    }
}

When you define your type

type MyResult<T> = Result<T, MyError>;

You actually define your type to be an unsized type as MyError is not a concrete type, but a trait. But, the implementation of Result<T, E> states

impl<T, E> Result<T, E> where E: Debug {
    /* ... */
}

Which implicitly requires E to be a sized type. Thus in your case, as it is not, the implementation is invalid and unavailable (actually, most if not all of the implementation of Result<T, E> requires T and E to be sized, so an unsized Result is not very useful).

The simplest fix in your case is to put your error in a Box , like this:

type MyResult<T> = Result<T, Box<MyError>>;
链接地址: http://www.djcxy.com/p/85676.html

上一篇: 为什么在这个html / css / jquery中注册了两个点击事件

下一篇: 结果类型不在名为`unwrap`的作用域中实现方法