我正在尝试使用Hyper和r2d2在 Rust 中构建一个小型 Web 服务,但我遇到了一些关于特征的问题。我无法解析编译器抛出的错误消息,所以我希望有人能帮助我。
考虑以下代码:
extern crate hyper;
extern crate postgres;
extern crate r2d2;
extern crate r2d2_postgres;
use hyper::Server;
use hyper::server::{Request,Response,Handler};
use r2d2_postgres::{SslMode, PostgresConnectionManager};
use r2d2::{Pool, PooledConnection};
use postgres::{Connection};
fn connect() -> Pool<PostgresConnectionManager>{
let config = r2d2::Config::default();
let conns = "postgres://abc:abc@localhost/abc";
let manager = PostgresConnectionManager::new(conns, SslMode::None).unwrap();
let pool = r2d2::Pool::new(config, manager).unwrap();
return pool;
}
fn hello(pool: Pool<PostgresConnectionManager>, req: Request, res: Response) {
res.send(b"Hello world").unwrap();
}
fn main() {
let pool = connect();
let dispatch = move |req: Request, res: Response| hello(pool, req, res);
Server::http("127.0.0.1:3000").unwrap().handle(dispatch).unwrap();
}
我的目标是pool
在函数中使用hello
. 通过使用闭包,我想,我可以传递一个环境变量,同时仍然不辜负 Hyper 的期望。不幸的是,我收到以下错误:
src/main.rs:28:45: 28:61 error: the trait `for<'r, 'r, 'r> core::ops::Fn<(hyper::server::request::Request<'r, 'r>, hyper::server::response::Response<'r>)>` is not implemented for the type `[closure@src/main.rs:27:20: 27:76 pool:r2d2::Pool<r2d2_postgres::PostgresConnectionManager>]` [E0277]
src/main.rs:28 Server::http("127.0.0.1:3000").unwrap().handle(dispatch).unwrap();
^~~~~~~~~~~~~~~~
src/main.rs:28:45: 28:61 help: run `rustc --explain E0277` to see a detailed explanation
error: aborting due to previous error
这取决于pool
. 例如,如果我尝试传递一个i64
,一切都会膨胀,编译器不会抱怨。