PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 14, 2022

[FIXED] What is await with question mark (await?) in Rust?

 November 14, 2022     async-await, error-handling, rust     No comments   

Issue

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:

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 ?



Answered By - cameron1024
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing