在Go中,我可以从函数返回一个函数,如下所示:
func newHandler(arg string) http.HandlerFunc {
return service.Handler(arg)
}
// in other files
handler := newHandler(config.Arg)
router.route("/", func(group *router.Group) {
group.GET("", handler)
})在铁锈真的很难今天我明白如何做到这一点。我拼命地用这样的代码:
use axum::{handler::Handler, response::Html, response::IntoResponse, routing::get, Router};
fn new_handler(arg: &str) {
async fn custom_handler() -> impl IntoResponse {
Html(source(HandlerConfig::new(arg)))
}
}
let handler = new_handler(&config.arg);
let router = Router::new().route("/", get(handler))但我知道这个错误:
error[E0277]: the trait bound `(): Handler<_, _>` is not satisfied
--> src\router.rs:22:50
|
22 | router = router.route("/", get(handler));
| --- ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Handler<_, _>` is not implemented for `()`
| |
| required by a bound introduced by this call
|
note: required by a bound in `axum::routing::get`
--> C:\Users\Fred\.cargo\registry\src\github.com-1ecc6299db9ec823\axum-0.5.4\src\routing\method_routing.rs:394:1
|
394 | top_level_handler_fn!(get, GET);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `axum::routing::get`如果我使用这段代码,它会工作:
async fn custom_handler() -> impl IntoResponse {
Html(source(HandlerConfig::new(arg)))
}
let router = Router::new().route("/", get(custom_handler))为什么会有这个错误?
发布于 2022-05-08 00:15:44
所以这里发生了几件事。当您执行以下操作时:
fn new_handler(arg: &str) {
async fn custom_handler() -> impl IntoResponse {
Html(source(HandlerConfig::new(arg)))
}
}您不是在“返回一个函数”,而是在另一个函数中声明一个异步函数,而不返回任何内容。锈蚀中的"Nothing“是单元类型(),这就是为什么没有为()实现这样和这样的特性时会出现错误。此外,不能将new_handler中的参数new_handler传递给new_handler中声明的任何函数。你可能想做的是这样的事情:
fn new_handler(arg: &str) -> _ {
|| async {
Html(source(HandlerConfig::new(arg)))
}
}但是,现在的问题是new_handler的返回类型。非正式地说,这种闭包的类型是impl Fn() -> (impl Future<Output = impl IntoResponse>) + '_。这是因为函数async fn foo() -> T的“类型”本质上是fn() -> FooFut,其中FooFut是实现Future<Output = T>的不透明类型。如果尝试将其作为返回类型,则只允许在某些地方使用impl Trait,就会得到一个编译器错误。归根结底,你不能嵌套存在主义类型。
您试图从Go中模仿的模式是生锈的非模式,所以我将避免将您的Go代码翻译得如此字面意思。工作的代码看起来要生疏得多,所以我会坚持这样做。
https://stackoverflow.com/questions/72156913
复制相似问题