预期的不透明类型,发现枚举“Result”

Dol*_*hin 1 rust

当我想像这样匹配 Rust 中函数的结果时:

#[get("/v1/user")]
pub fn user_info(){
    match get_user_info(16){
        Ok(sk) => {
            info!("get user info success:" + sk)
        },
        Err(e) => {
            info!("error:" + e)
        },
    }
}
Run Code Online (Sandbox Code Playgroud)

显示这样的错误:

error[E0308]: mismatched types
  --> src/biz/music/test_controller.rs:53:9
   |
53 |         Ok(sk) => {
   |         ^^^^^^ expected opaque type, found enum `Result`
   |
note: while checking the return type of the `async fn`
  --> src/common/net/rest_client.rs:4:50
   |
4  | pub async fn get_user_info(input_user_id:i64) -> Result<(), Box<dyn std::error::Error>> {
   |                                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ checked the `Output` of this `async fn`, expected opaque type
   = note: expected opaque type `impl std::future::Future`
                     found enum `Result<_, _>`

error[E0308]: mismatched types
  --> src/biz/music/test_controller.rs:57:9
   |
57 |         Err(e) => {
   |         ^^^^^^ expected opaque type, found enum `Result`
   |
note: while checking the return type of the `async fn`
  --> src/common/net/rest_client.rs:4:50
Run Code Online (Sandbox Code Playgroud)

这是我的get_user_info功能:

pub async fn get_user_info(input_user_id:i64) -> Result<(), Box<dyn std::error::Error>> {
    let url = "http://dolphin-post-service.reddwarf-pro.svc.cluster.local:11014/post/user/";
    let uid = string_to_static_str(input_user_id.to_string());
    let resp = reqwest::get(format!("{}{}", url, uid))
        .await?
        .json::<HashMap<String, String>>()
        .await?;
    println!("{:#?}", resp);
    Ok(())
}
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题,我在网上搜索并告诉我该函数是return a Future,但我await在rust中没有找到关键字,如何处理这种情况?我应该怎么做才能让它发挥作用?

Abd*_*P M 6

返回的值async fn是一个Future。Future一种可以产生值的异步计算(尽管该值可能为空,例如 ())同样在 内部async fn,您可以用来.await等待另一个实现Future特征的类型的完成。

get_user_info是一个异步函数(返回一个 Future)。因此,要获得实际结果,您必须使用awaitwhich将等待完成get_user_info

pub async fn user_info(){
    match get_user_info(16).await {
        Ok(()) => {
            dbg!("get user info success:");
        },
        Err(e) => {
            dbg!("error:");
        },
    }
}

  • 很好地使用“&lt;pre&gt;”来强调添加的关键字。 (2认同)