expected opaque type, found enum `Result`

Viewed 2128

when I want to match the result of a function in rust like this:

#[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)
        },
    }
}

shows error like this:

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

and this is my get_user_info function:

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(())
}

how to solve this problem, I am search from internet and tell me that the function is return a Future, but I did not found a await keyword in rust, how to handle this situation? what should I do to make it work?

1 Answers

The value returned by async fn is a Future. A Future is an asynchronous computation that can produce a value (although that value may be empty, e.g. ()). Also inside an async fn, you can use .await to wait for the completion of another type that implements the Future trait.

get_user_info is an async function(which returns a Future). So to get the actual result, you have to use await which will wait for the completion of get_user_info

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