Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

You're probably right, I must be missing something. I'm also still on futures 0.1 because I'm still porting it to std::futures.

Here's an example of what I was discussing:

https://github.com/dmm/exopticon/blob/c40d14c80c150ef6270732...

The idea is that I want to implement a relative ptz move on a camera but some cameras have a broken relative move implementation so in that case we instead use a continuous move + a delay + a continuous stop. The final case is when a camera has no ptz it returns Http::NotFound.



If you have

    if cond {
        Box::new(future_a)
    }
    else {
        Box::new(future_b)
    }
then by default, the type of the first Box will be concrete Box<FutureA> rather than Box<dyn Future>, which is why you'll get a type error that Box<FutureB> != Box<FutureA>

You'll need to coerce the first expression to Box<dyn Future>. The compiler will auto-coerce the other one.

    if cond { Box::new(future_a) as Box<dyn Future<...>> } else { Box::new(future_b) }
See https://play.rust-lang.org/?version=stable&mode=debug&editio...

(This auto-coercion also applies to other situations where the type of an expression must match the previous one's, such as with a slice literal where the first element dictates the types of the rest.)

You don't need to coerce if the compiler can infer that the whole if-expr must be of Box<dyn Future> type. This happens when the if-expr is being returned directly and thus must have the same type as the function's return type, or it's being assigned to the binding and the binding has been previously inferred to have (or explicitly has) Box<dyn Future> type. You can test this in the playground by returning the if-expr directly instead of binding it to `result`.


A more stylistic pattern for this is to give the binding a type so that the coercion of the if/else expression works automatically instead of using `as`.

Also, there's work being done so that this won't be needed by deferring evaluation of expressions until the whole body has already been evaluated so that inference with the naïve code will work at some unspecified time in the future.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: