What does ?? do in rust?

Will

Here is an example of it in action:

let msg = stream.next().await.context("expected a message")??;

Is it just ? being done twice? If so why does it need to be done in this case?

Francis Gagné

Yes, it's just ? being done twice; there is no ?? operator.

stream is a WsStream. WsStream is a type defined in the same module. WsStream implements Stream.

stream.next() invokes StreamExt::next, which returns a future that yields Option<Self::Item>. Self::Item is defined to be tungstenite::Result<Message> (= Result<Message, tungstenite::Error>) for WsStream. This means that the result of stream.next().await is of type Option<Result<Message, tungstenite::Error>>.

Then, context is applied on the value. Context is implemented for Option<T> and for Result<T, E>, but the output is always a Result. However, context doesn't flatten anything, so we end up with Result<Result<Message, tungstenite::Error>, anyhow::Error>. The two uses of ? therefore serve to handle the two levels of Results.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive