rust - Rust 中将函数转换为 trait 的机制是什么?
问题描述
来自 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<(), _, _>
.
anasync fn
是函数的语法糖,它返回Future
某种类型的 a (并且可以在.await
内部使用),所以async fn index() -> impl Responder
实现Fn() -> impl Future<Output = impl Responder>
所以它也实现Factory<(), _, _>
.
推荐阅读
- python - 减少因式分解代码的执行时间
- python - 结合 2 个不同的数据框并仅获取相同的数据
- c++ - 弹性解析符号 - 复杂符号
- python - 如何将非常大的 json 流文件解析为有效的 JSON
- reactjs - 我们可以在 reactjs 或 jquery 中使用 excel 函数吗?
- ios - 在 Swift 中使用静态函数来处理弹出窗口是不是很糟糕?
- ruby-on-rails - Rails 邮件程序不工作 Net::OpenTimeout
- telerik - Fiddler 在捕获流量时显示划掉的文本
- c - C中联合后的“++”是什么意思?
- sql - 从十进制 (8, 0) 格式的日期获取 n-3 或 nx 个月(约 90 天前),在 SQL Server 和 DB2 中具有年份变化影响