rust - 如何在火箭中使用结构的方法作为处理程序
问题描述
#[derive(Debug, Clone)]
struct Author<T: Persister + Send + Sync + Clone> {
dao: T,
}
impl<T: Persister + Send + Sync + Clone> Author<T> {
fn new(dao: T) -> Self {
Author { dao: dao }
}
fn handle_sign_up<'r>(&self, request: &'r Request, data: Data) -> Outcome<'r> {
Outcome::Success(Response::new())
}
}
impl<T> Handler for Author<T>
where
T: Persister + Send + Sync + Clone + 'static,
{
fn handle<'r>(&self, request: &'r Request, data: Data) -> Outcome<'r> {
Outcome::Success(Response::new())
}
}
impl<T: Persister + Send + Sync + Clone + 'static> Into<Vec<Route>> for Author<T> {
fn into(self) -> Vec<Route> {
vec![Route::new(rocket::http::Method::Post, "/", self)]
}
}
fn main() {
let dao = Dao::new("mysql://user:password@localhost/test".to_owned()).unwrap();
let author = Author::new(dao);
rocket::ignite().mount("/", author).launch();
}
我想使用Author
(例如Author::handle_sign_up
)的方法作为路由的处理程序,但它不起作用。我尝试使用如下所示的 clouser
impl<T: Persister + Send + Sync + Clone + 'static> Into<Vec<Route>> for Author<T> {
fn into(self) -> Vec<Route> {
let p = |req, data| self.handle_sign_up(req, data);
vec![Route::new(rocket::http::Method::Post, "/", p)]
}
}
, 编译器报告了一个生命周期错误
不匹配的类型 预期的类型
for<'r, 's> Fn<(&'r rocket::Request<'s>, rocket::Data)>
找到的类型Fn<(&rocket::Request<'_>, rocket::Data)>
有没有办法实现它?
解决方案
问题|req, data| self.handle_sign_up(req, data)
在于编译器会推断参数类型的生命周期,但在这里会出错。&'r Request
和之间的关系Outcome<'r>
是必需的和缺乏的。
不幸的是,您不能显式地注释闭包的生命周期。
一种解决方法(如上面链接中的一个答案所建议的)是使用一个辅助函数,它不做任何事情,但鼓励编译器推断正确的签名:
fn as_handler_func<F>(f: F) -> F
where
F: for<'r> Fn(&'r Request, Data) -> Outcome<'r>,
{
f
}
impl<T: Send + Sync + Clone + 'static> Into<Vec<Route>> for Author<T> {
fn into(self) -> Vec<Route> {
let p = as_handler_fn(move |req, data| self.handle_sign_up(req, data));
vec![Route::new(rocket::http::Method::Post, "/", p)]
}
}
附带说明:我不是 Rocket 方面的专家,但我相信如果你像这样实现Into<Vec<Route>>
,Author
你可能也不想这样做impl Handler
。
推荐阅读
- amazon-dynamodb - 这是一个糟糕的 DynamoDB 数据库架构吗?
- python - 如何计算模糊字符串匹配中的分数?
- flutter - TextFormField 的自定义控制器在焦点移除时清除输入的文本 - Flutter
- reactjs - 如何在没有身份验证的情况下让访客访问套接字?
- docker - 使用当前用户在 Docker 中获取 /root/.zshrc
- keras - DenseNet with Keras UnknownError:无法获得卷积算法
- python - assertLog 未捕获日志记录
- python - MongoEngine fieldDoesNotExist 错误,但实际上是
- reactjs - 如何在 ReactJs 卡中包含 s3image
- xcode - XCode - 如何重置/“删除”从 XCode 运行的 mac os 应用程序(类似于在 ios 模拟器中删除应用程序)?