Re:Announcing Rust 1.22
by masklinn on Thursday November 23, 2017 @06:58AM
(#15764475)
It's a shortcut for "early-returning" in error cases
> Was more boilerplate necessary in the example before?
Somewhat yes, the original use case is Result types (and the try! macro):
let v = func()?;
expands to
let v = match func() {
Ok(v) => v,
Err(e) => return Err(From::from(e))
};
that is it "unwraps" a successful result, and barring one it directly returns from the current function (having possibly converted the error). Before 1.22, doing that with an Option would be:
let v = match func() {
Some(v) => v,
None => return None
};
or
let v = if let Some(v) { v } else { return None };
after 1.22, this becomes
let v = func()?;
as well.
edit: note that this is quite different from the behaviour of the ? operator in languages like C# or Swift where it compounds into "null-safe" operators, the most famous being the null-safe navigation operator "?."[0], these are closer to the monadic bind, which in Rust is called "and_then".
> Was more boilerplate necessary in the example before?
Somewhat yes, the original use case is Result types (and the try! macro):
expands to that is it "unwraps" a successful result, and barring one it directly returns from the current function (having possibly converted the error). Before 1.22, doing that with an Option would be: or after 1.22, this becomes as well.edit: note that this is quite different from the behaviour of the ? operator in languages like C# or Swift where it compounds into "null-safe" operators, the most famous being the null-safe navigation operator "?."[0], these are closer to the monadic bind, which in Rust is called "and_then".
[0] https://en.wikipedia.org/wiki/Safe_navigation_operator