首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从axum服务器路由调用struct方法?

如何从axum服务器路由调用struct方法?
EN

Stack Overflow用户
提问于 2022-08-05 14:14:40
回答 1查看 302关注 0票数 2

我希望实例化一个struct实例,然后在api路由中调用该实例的方法。下面是我想要的一个例子,但是它会导致一个错误:

代码语言:javascript
复制
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();
}
代码语言:javascript
复制
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

我试图通过定义一个调用实例方法的函数来解决这个问题:

代码语言:javascript
复制
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服务器路由调用实例方法?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-05 15:03:43

您可以将api移到闭包中,然后进入将来:

代码语言:javascript
复制
let hello_method = move || async move { 
    match api.hello().await {
        Ok(response) => response,
        Err(_) => "error".to_owned(),
    }
};

或使用nightly特性#![feature(async_closure)]

代码语言:javascript
复制
let hello_method = async move || { 
    match api.hello().await {
        Ok(response) => response,
        Err(_) => "error".to_owned(),
    }
};
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73251151

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档