3 ms·
> `let else` looks strange to my eyes on first glance AIUI, this is a rather specialized feature that only supports diverging code in the "else" block. I assu
by zozbot234 4y ago
> `let else` looks strange to my eyes on first glance
AIUI, this is a rather specialized feature that only supports diverging code in the "else" block. I assume that the weird syntax was purposely chosen to suggest something like that.
- queuebert 4y agoHow does this improve on binding the `Err`? Edit: I see now in the first example: let (Some(count_str), Some(item)) = (it.next(), it.next()) else { panic!("Can't segment count item pair: '{s}'"); }; Binding the error here would be much verbose, since both must succeed. Edit2: Doh, obviously `None` in this example, not `Err`.
- kibwen 4y agoI don't find the syntax weird, I think it's perfectly cromulent with the existing capabilities. To wit, pattern matching in `let` has always been possible: let (x, y) = (1, 2); ...But only for patterns that can never fail. For enums, not all patterns are irrefutable: let Some(x) = Some(42); // error, Rust can't tell that RHS isn't `None` Note that some languages with pattern matching do allow the above, e.g. OCaml does, and just panics if the match doesn't succeed (so equivalent to `let x = Some(42).unwrap()` in Rust). But Rust favors exhaustive pattern matching, so that wasn't a good fit. The way that Rust solves this is via `if`-style constructs. So you already have `if let`: if let Some(x) = Some(42) { // `x` exists in here } This produces an inner scope where the contents of the enum are bound. And you can use `else` here as well: if let Some(x) = Some(42) { // `x` exists in here } else { // branch where `x` doesn't exist } So the `let else` syntax feels like a natural continuation to me: let Some(x) = Some(42) else { // branch where `x` doesn't exist } // `x` exists here This reduces the nesting required in several common cases of using enums, which makes code easier to read. (Of course, the interesting thing is that since `x` exists in the outer scope, the compiler requires the inner scope to never reach the outer scope (it must "diverge", by returning or panicking or infinite looping or whatever), which is an extra restriction above what a normal `if else` requires.)
- tialaramex 4y agoSo it just checks the type of the "diverging" else block is Never or something ?
- kibwen 4y agoYes, the `else` branch in `let else` is required to diverge.