来自actix-web的示例如下:
use actix_web::{web, App, Responder, HttpServer};
async fn index() -> impl Responder {
"Hello world!"
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new().service(
web::scope("/app").route("/index.html", web::get().to(index)),
)
})
.bind("127.0.0.1:8088")?
.run()
.await
}
我的问题是该语句如何to(index)
在Rust中工作。
查看源代码,to
我们看到:
pub fn to<F, T, R, U>(mut self, handler: F) -> Self
where
F: Factory<T, R, U>,
// --- snip
其中Factory
定义为:
pub trait Factory<T, R, O>: Clone + 'static
where
R: Future<Output = O>,
O: Responder,
{
fn call(&self, param: T) -> R;
}
函数async fn index() -> impl Responder
转换成Factory<T, R, O>
什么机制?
在您的代码段之后有一个特征实现:
impl<F, R, O> Factory<(), R, O> for F
where
F: Fn() -> R + Clone + 'static,
R: Future<Output = O>,
O: Responder,
{
fn call(&self, _: ()) -> R {
(self)()
}
}
可以理解为:如果一个类型F
实现了,Fn() -> Future<Output = impl Responder> + ...
那么它也实现了Factory<(), _, _>
。
而async fn
对于返回Future
某种a(并且可以在.await
内部使用)的函数来说,它是一个语法糖,因此async fn index() -> impl Responder
实现Fn() -> impl Future<Output = impl Responder>
也实现了Factory<(), _, _>
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句