You were pretty close with your hypothetical syntax! You can write:
let Some(y) = x else { do_stuff(); return };
I think it was a fairly recent addition to Rust.Thank dog for that. I feel like I even read the release notes for that but it was while I hadn’t been touching a specific codebase with loads of early returns. Thanks for pointing this out!
Re:Nibbles of Rust – Restructuring Patterns
by chrismorgan on Sunday April 16, 2023 @09:53AM
(#35590045)
let-else was stabilised in 1.65.0, released 2022-11-03.
Re:Nibbles of Rust – Restructuring Patterns
by metadat on Sunday April 16, 2023 @02:29PM
(#35592840)
What determines whether `let Some(y) = x` evaluates to boolean true?
Re:Nibbles of Rust – Restructuring Patterns
by asherah on Sunday April 16, 2023 @02:47PM
(#35593067)
if x is `Some`, then `y` is set to the inner value and the following block occurs. you can also use this with other enums - i don't remember off the top of my head if it works for all enums, but you can at least also use it with `Result`
It absolutely works for all patterns!
let MyEnum(foo, bar, baz) = input but otherwise { do some stuff return some value }
Point being I don’t have to check for MyEnum-ness twice (like with matches! + if let) and the indented code is for the exception (no match) not the norm.
Tho I … guess !matches(MyEnum{ .. }) is not the worst… but it’s annoying to have this pattern all over my code instead of as some encoded concept we all use