Hacker Newsnew | past | comments | ask | show | jobs | submit | frederico02's commentslogin

Nice article. Not everything is an expression in rust as the author mentioned though.


True, but almost everything is. The Book's entry on statements is like four paragraphs, while the entire rest of that chapter is about expressions.

For example all Rust's loops are expressions. This isn't very useful in many cases, but breaking an ordinary loop can yield a value, so e.g. you can loop checking all the integers until you find one you like, and then return it as the value of the loop. Nice.


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.


The 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.


I added an 'almost' caveat to the text - thanks for the note.


What's not an expression?


There aren't many; basically just variable declarations: https://doc.rust-lang.org/reference/statements.html


meetup.com



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: