1

Here's an example:

#[tokio::main]
async fn main() {
    let args: Vec<String> = env::args().collect();

    let body = get_pokemon(&args[1]).await;

    // here

    let pokemon = parse_response(body);
}

struct Pokemon {}

async fn get_pokemon(pokemon: &String) -> reqwest::Result<String> {
    let body = reqwest::get(format!("https://pokeapi.co/api/v2/pokemon/{}", pokemon))
        .await?
        .text()
        .await?;

    Ok(body)
}

async fn parse_response(response: String) -> Pokemon {}

body is of type Result<String, Error>, is there a way to match what the get_pokemon function returns with the match keyword or something similar? i.e. if it returns an error then do this, if a String, do this, etc.

steamsy
  • 104
  • 1
  • 8
  • 1
    Yes, using `match` is a pretty common pattern as seen [here](https://doc.rust-lang.org/std/result/). – squiguy Sep 06 '21 at 21:35
  • I think that's get_pokemon should be return an Result. You can found several example in https://dev.to/pintuch/rust-reqwest-examples-10ff – Zeppi Sep 07 '21 at 06:52

1 Answers1

1

with Rust it is very common to match for the return type of a function that returns Result<T,E> where T is any type that is returned on success and E is an error type that is returned in case of an error. What you could do is:

match body {
   Ok(pokemon) => {
      parse_response(body);//looking at get_pokemon `pokemon` will be of type String here
   }
   Err(e) => { // 'e' will be your error type
      eprintln!("Error! {:?}", e)
   }
}

Your function is returning a reqwest::Result<String>. Without having worked with reqwest I cannot give advice on handling this specific Result. This declaration looks similar to std::io::Result<T> which is a shorthand for std::io::Result<T, std::io::Error>. That means You should expect your pokemon to be of type String or some error type.

MYZ
  • 331
  • 2
  • 10