如何创建函数以返回具有扭曲的路线



我正在尝试重构REST服务器以使用模块。我在确定要返回的类型时遇到了很多困难。考虑下面的简单示例:

main.rs

use warp_server::routes::routers::get_routes;
#[tokio::main]
async fn main() {
let routes = get_routes();
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}

routes.rs

pub mod routers {
use warp::Filter;
pub fn get_routes() -> Box<dyn Filter> {
Box::new(warp::any().map(|| "Hello, World!"))
}
}

这不会编译,因为返回类型与返回的类型不匹配。

error[E0191]: the value of the associated types `Error` (from trait `warp::filter::FilterBase`), `Extract` (from trait `warp::filter::FilterBase`), `Future` (from trait `warp::filter::FilterBase`) must be specified
--> src/routes.rs:4:36
|
4 |     pub fn get_routes() -> Box<dyn Filter> {
|                                    ^^^^^^ help: specify the associated types: `Filter<Extract = Type, Error = Type, Future = Type>`

我试过很多东西。我首先想到的是:

pub mod routers {
use warp::Filter;
pub fn get_routes() -> impl Filter {
warp::any().map(|| "Hello, World!")
}
}

但我得到了这个编译错误:

error[E0277]: the trait bound `impl warp::Filter: Clone` is not satisfied
--> src/main.rs:6:17
|
6  |     warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
|                 ^^^^^^ the trait `Clone` is not implemented for `impl warp::Filter`
| 
::: /Users/stephen.gibson/.cargo/registry/src/github.com-1ecc6299db9ec823/warp-0.3.1/src/server.rs:25:17
|
25 |     F: Filter + Clone + Send + Sync + 'static,
|                 ----- required by this bound in `serve`

我真的很困惑该怎么做。显然,我仍然对Rust的泛型和特性感到困惑。

一个简单的方法是使用带有一些调整的impl Filter

use warp::{Filter, Rejection, Reply};
fn get_routes() -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
warp::any().map(|| "Hello, World!")
}

相关内容

  • 没有找到相关文章

最新更新