Expressions evaluate to a value, and semicolons take an expression, throw away its value, and evaluate to () instead. That's it.
The other behaviors you're talking about fall out of these semantics, but are also different than what you've said; functions evaluate to a value, so the final expression's value determines the value it evaluates to, but you cannot "implicitly return" from the middle of a function by dropping a ;, for example.
fn foo(x: i32) -> i32 { x * 2 }Thinking of them as implicit returns leads people to believe they can write code like
fn foo(x: bool) -> i32 {
if x {
5
}
// more code
and then they're confused when this doesn't work. if(foo = 5) {
...
}
They are easy to mess up when you're getting started, but they're also very easy to fix because they'll basically always result in a clear compiler error. If "builds failing" are annoying for you, you probably aren't using an IDE with inline errors, and with Rust you absolutely should be doing that or you'll have a bad time. if(foo = 5) {
...
}
You don't need the rust style expression/statement distinction to catch this. Many languages will catch this at compile time since "foo = 5" does not evaluate to a boolean.I know that it's relatively easy to catch this error in Rust, and it is at most a minor annoyance, but it still feels like a clear step backwards after working with languages which don't require semicolons at all.
In most C-like languages, this expression is valid: the whole thing evaluates to "5", which has a truthiness. Some "clever" programmers use this pattern intentionally in loops to save a line of code, especially in the C/C++ world. For example:
while(currentNode = currentNode.next) {
...
}
When currentNode becomes null, the expression/statement becomes falsy, and the loop terminates. I absolutely love the way Rust systematically disallows shaky syntax tricks like this.My point is, there are plenty of examples of languages that show that you don't need to add semicolons to almost every line of your program just to avoid this one potential error.
I think the only language I know of that disallows assignment in them is python, and it's not because assignment evaluates to something other than boolean, python is happen to evaluate the 'truthiness' of certain types. And funnily enough, they are going to add this back in to python 3 I believe, using a different operator.
I've found that Rust flows much more nicely when you just embrace an imperative style "by default". That's its native tongue; the functional stuff is more of an exception.
Those of us used to multi-paradigm languages have taught ourselves that imperative == bad (actual for-loops! egads!), but the thing is, Rust is specifically designed to make it not-bad. It gives you all these tools to carefully control and limit mutability, so you can do imperative stuff with much less fear. It takes getting used to but in my (limited) experience this mindset significantly reduces friction when working with Rust.