Result type does not implement method in scope nam

2019-06-17 07:29发布

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()
    }
}

标签: rust
1条回答
ら.Afraid
2楼-- · 2019-06-17 07:56

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>>;
查看更多
登录 后发表回答