gpt4 book ai didi

rust - 在Rust中将函数转换为特征的机制是什么?

转载 作者:行者123 更新时间:2023-12-03 11:23:25 24 4
gpt4 key购买 nike

example from 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中的工作方式。
查看 source code for to ,我们看到:
pub fn to<F, T, R, U>(mut self, handler: F) -> Self
where
F: Factory<T, R, U>,
// --- snip
其中 Factory is defined as:
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>的机制是什么?

最佳答案

您的代码段后面有an implementation of the trait:

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(并且可以在内部使用 .await),因此 async fn index() -> impl Responder实现 Fn() -> impl Future<Output = impl Responder>,因此它也实现 Factory<(), _, _>

关于rust - 在Rust中将函数转换为特征的机制是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63828267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com