2

希望有人可以帮助我理解为什么warp使用这样的单一路线运行编译得很好:

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // GET /stats
    let stats = warp::get()
        .and(warp::path("stats"))
        .map(|| {
            let mut sys = System::new_all();
            sys.refresh_all();

            let local = LocalSystem::from_sys(&sys);
            warp::reply::json(&local);
        });

    // GET /
    let index = warp::get()
        .and(warp::path::end())
        .map(|| warp::reply::json(&last_ten_logs()));

    warp::serve(index).run(([127, 0, 0, 1], 4000)).await;

    Ok(())
}

但是像 repo 中的示例那样更改该warp::serve()行以提供两条路由会导致编译错误:

error[E0277]: the trait bound `(): Reply` is not satisfied
   --> src/main.rs:140:17
    |
140 |     warp::serve(stats.or(index)).run(([127, 0, 0, 1], 4000)).await;
    |     ----------- ^^^^^^^^^^^^^^^ the trait `Reply` is not implemented for `()`
    |     |
    |     required by a bound introduced by this call
    |
    = note: required because of the requirements on the impl of `Reply` for `((),)`
    = note: 2 redundant requirements hidden
    = note: required because of the requirements on the impl of `Reply` for `(warp::generic::Either<((),), (Json,)>,)`

我不明白编译器要求我改变什么。

4

1 回答 1

1

The error is explicit:

the trait Reply is not implemented for ()

The problem is that your stats endpoint do not return anything, just remove the last ; so it gets returned as the last expresion in the closure:

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // GET /stats
    let stats = warp::get()
        .and(warp::path("stats"))
        .map(|| {
            let mut sys = System::new_all();
            sys.refresh_all();

            let local = LocalSystem::from_sys(&sys);
            warp::reply::json(&local)
        });
    ...
}
于 2022-01-10T18:50:12.900 回答