3 ms·
Nice tip. 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 w
by rtpg 3y ago
Nice tip.
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)
- spease 3y agoYou mean like ‘matches!’? https://doc.rust-lang.org/std/macro.matches.html https://doc.rust-lang.org/std/macro.matches.html
- rtpg 3y agoWhat 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
- ljsb 3y agoYou 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.
- rtpg 3y agoThank 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!
- chrismorgan 3y agolet-else was stabilised in 1.65.0, released 2022-11-03.
- metadat 3y agoWhat determines whether `let Some(y) = x` evaluates to boolean true?
- bombela 3y agoThe fact that the pattern matches. Here the type being matched is: enum Option<T> { None, Some(T) } let x = Some(42); let Some(y) = x else { panic!("None") };
- asherah 3y agoif 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`
- jeffdn 3y agoIt absolutely works for all patterns!
- e-dant 3y agoUse combinators!