Reputation: 134
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.
Upvotes: 1
Views: 1252
Reputation: 359
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.
Upvotes: 1