rustrust-warp

Why can't I use a multi-line builder pattern


I have started looking into Rust (and Warp) just a few days ago. I can't get into my head the following:

Given the following endpoints

    let hi = warp::path("hi");
    let bye = warp::path("bye");
    let howdy = warp::path("howdy");

Why is the following ok

    let routes = hi.or(bye).or(howdy);

But not the following:

    let mut routes = hi.or(bye);
    routes = routes.or(howdy);

Which throws the compile error:

error[E0308]: mismatched types 
   --> src/lib.rs:64:14
    |
63  |     let mut routes = hi.or(bye);
    |                      -------------------- expected due to this value
64  |     routes = routes.or(howdy);
    |              ^^^^^^^^^^^^^^^^ expected struct `warp::filter::and_then::AndThen`, found struct `warp::filter::or::Or` 

Solution

  • or() wraps in a new type. You can use shadowing:

    let routes = hi.or(bye);
    let routes = routes.or(howdy);
    

    If you really need them to have the same type (e.g. for usage in a loop), you can use the boxed() method to create a trait object:

    let mut routes = hi.or(bye).unify().boxed();
    routes = routes.or(howdy).unify().boxed();