Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed to infer type when using Result::map and Box

Tags:

rust

Why won't this compile?

trait T {}

fn f<U: 'static + T, V, E>(f2: V) -> impl Fn() -> Result<Box<dyn T>, E>
where
    V: Fn() -> Result<U, E>,
{
    move || -> Result<Box<dyn T>, E> { f2().map(Box::new) }
}

The error message is:

error[E0308]: mismatched types
 --> src/lib.rs:7:40
  |
7 |     move || -> Result<Box<dyn T>, E> { f2().map(Box::new) }
  |                                        ^^^^^^^^^^^^^^^^^^ expected trait T, found type parameter
  |
  = note: expected type `std::result::Result<std::boxed::Box<(dyn T + 'static)>, _>`
             found type `std::result::Result<std::boxed::Box<U>, _>`
  = help: type parameters must be constrained to match other types
  = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters

This version is ok:

trait T {}

fn f<U: 'static + T, V, E>(f2: V) -> impl Fn() -> Result<Box<dyn T>, E>
where
    V: Fn() -> Result<U, E>,
{
    move || -> Result<Box<dyn T>, E> {
        match f2() {
            Ok(result) => Ok(Box::new(result)),
            Err(e) => Err(e),
        }
    }
}

In my opinion, (dyn T + 'static) and U are the same; am I right?

I'm using rustc 1.39.0-nightly (f0b58fcf0 2019-09-11).

like image 570
龙方淞 Avatar asked Oct 20 '25 04:10

龙方淞


1 Answers

It's a limitation and I don't know if it will compile one day. The reason is that Rust doesn't know to convert between the two Result types, (dyn T + 'static) and U are totally different things. If this acceptable you can do f2().map(|x| Box::new(x) as _).

The cast will allow the compiler to transform U into (dyn T + 'static) before put it in the result, we don't need to explicit the cast type the compiler inference will do it for us (on most case).

A trait object can be obtained from a pointer to a concrete type that implements the trait by casting it (e.g. &x as &Foo)

See dynamic dispatch section of the book (didn't find any information in the new book).

like image 92
Stargateur Avatar answered Oct 22 '25 05:10

Stargateur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!