问题描述
我正在尝试重构我的 REST 服务器以使用模块。我在确定要返回的类型时遇到了很多麻烦。考虑下面的简单示例:
main.rs
use warp_server::routes::routers::get_routes;
#[tokio::main]
async fn main() {
let routes = get_routes();
warp::serve(routes).run(([127,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,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!")
}