Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is await with question mark (await?) in Rust?

I read this portion of the book on Async programming in Rust https://rust-lang.github.io/async-book/03_async_await/01_chapter.html

I see the mention of the .await syntax,

and then I later saw a blog where reqwest is being used to fetch a url. The code looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let resp200 = client.get("https://httpbin.org/ip")
    .header(CONTENT_TYPE, "application/json")
    .send()
    .await?
    .json::<GETAPIResponse>()
    .await?;

I do not understand the .await?. I know ? is a shorthand for extracting the Ok case or returning from the function with an Error. But as far as I am aware, .await does not return Result so how is it possible to do .await with ?

>Solution :

.await simply turns a impl Future<Output = T> into a T.

? (mostly) turns a Result<T, E> into a T.

When put together, .await? turns a impl Future<Output = Result<T, E>> into a T.

The following code is equivalent:

let future = client.get("https://httpbin.org/ip")
    .header(CONTENT_TYPE, "application/json")
    .send();
let result: Result<_, _> = future.await;
let response: Response = result?;
let json_future = response.json();
let json_response: Result<_, _> = json_future.await;
let json = json_response?;

But, .await? is not a special operator. It’s literally just .await followed by ?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading