我希望实例化一个struct实例,然后在api路由中调用该实例的方法。下面是我想要的一个例子,但是它会导致一个错误:
use axum::{http::StatusCode, routing::get, Router, Server};
#[derive(Clone)]
struct Api {
name: String
}
impl Api {
async fn hello(&self) -> Result<String, StatusCode> {
Ok(format!("Hello {}!", self.name))
}
}
#[tokio::main]
async fn main() {
let api = Api { name: "Alice".to_owned() };
let app = Router::new()
.route("/hello-user", get(api.hello));
Server::bind(&([127, 0, 0, 1], 3000).into())
.serve(app.into_make_service())
.await
.unwrap();
}error[E0615]: attempted to take value of method `hello` on type `Api`
--> src\main.rs:19:39
|
19 | .route("/hello-user", get(api.hello));
| ^^^^^ method, not a field我试图通过定义一个调用实例方法的函数来解决这个问题:
let hello_method = move || async {
match api.hello().await {
Ok(response) => response,
Err(_) => "error".to_owned(),
}
};
let app = Router::new()
.route("/hello-user", get(hello_method));然而,有了这个,我得到了一个“一生可能还不够长”的错误。如何从axum服务器路由调用实例方法?
发布于 2022-08-05 15:03:43
您可以将api移到闭包中,然后进入将来:
let hello_method = move || async move {
match api.hello().await {
Ok(response) => response,
Err(_) => "error".to_owned(),
}
};或使用nightly特性#![feature(async_closure)]
let hello_method = async move || {
match api.hello().await {
Ok(response) => response,
Err(_) => "error".to_owned(),
}
};https://stackoverflow.com/questions/73251151
复制相似问题