简体   繁体   中英

Why does Rust expects an OK struct in Err in match?

So I have a following code that basically does a HTTP request using hyper library. Afterwards it decodes the json sent by the server. However, in Err(err) => {...} , Rust throws expected struct User, found () . Why does Rust expects a User struct to be returned in Err(err) => {...} ?

use hyper::body::Buf;
use hyper::Client;
use serde::Deserialize;

#[tokio::main]
async fn main() {
    let url = "http://jsonplaceholder.typicode.com/users/1"
        .parse()
        .unwrap();

    let user = match fetch_json(url).await {
        Ok(data) => data,
        Err(err) => {
            println!("Some error occured {}", err);
            // expected struct User, found ()
        }
    };
    // print users
    println!("users: {:#?}", user);
}

async fn fetch_json(url: hyper::Uri) -> Result<User, Box<dyn std::error::Error + Send + Sync>> {
    let client = Client::new();

    // Fetch the url...
    let res = client.get(url).await?;

    let response_code = res.status();

    // asynchronously aggregate the chunks of the body
    let body = hyper::body::aggregate(res).await?;

    // try to parse as json with serde_json
    let user = serde_json::from_reader(body.reader())?;

    Ok(user)
}

#[derive(Deserialize, Debug)]
struct User {
    id: i32,
    name: String,
}

Why does Rust expects a User struct to be returned in Err(err) => {...}

But the return type is Result<User, Box<dyn std::error::Error + Send + Sync>>

But it's not. Your Ok match arm returns data , which is User . So this has become the inferred type for user in let user = match fetch_json(url).await . That's why the compiler expects the same type to be returned from all other match arms too. You could provide an explicit type annotation to user , but that will only get you different errors until you fix the problem: inconsistent return types from match arms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM