Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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()
    }
}
like image 865
brandonchinn178 Avatar asked Jun 11 '15 17:06

brandonchinn178


1 Answers

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>>;
like image 97
Levans Avatar answered Sep 22 '22 22:09

Levans