4 ms·
Detail that sometimes bites me: the `loop` looping construct is an expression that can yield a value. `for` and `while` technically are expressions, but they ca
by sophacles 5y ago
Detail that sometimes bites me: the `loop` looping construct is an expression that can yield a value. `for` and `while` technically are expressions, but they can only ever yield `()` (unit type).
Coming from python, i feel doing something like this:
let x = for v in iter {
if cond(v) {
break v;
}
} else {
default_v
}
would be nice, but this was explicitly rejected by the core team. So for now anyway, only `loop` can break with value.
- tialaramex 5y agoThe thing is, loop gets to break with value because it otherwise doesn't end (so the type of the loop when it doesn't break is never aka ! and that's compatible with any type), but a for loop will always end anyway, so what's the value of the for loop when that happens? In your example code, I see there's an else clause on the for loop which is presumably special syntax so as to provide the value if it doesn't break, but that feels pretty clumsy to me and I'm not sure there are many cases where it's more readable than what I'd do now. If I could see a nice way to do it without such clumsy special syntax, I'd favour this, but with the else syntax (or some equivalent) it feels like it doesn't pull its weight.