You mean like ‘matches!’?
What I want is..
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
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!
I honestly am a bit frustrated with Rusts pattern matching ergonomics, cuz it ends up requiring me to introduce indentation in places where I don’t want it, mainly to futz around with unwrapping structures or the like.
Lots of helper methods exist on standard library enumerations but I really want there to be some nice built in macros to just give me the innards when I need it, and have a control flow block for when I _cant_ pattern match (and thus want to do an early return or blow up). Maybe this already exists!
Too much indentation makes languages unfun (see every lisp struggle with this with name binding)