25 ms·
if(foo = 5) { ... } You don't need the rust style expression/statement distinction to catch this. Many languages will catch this at compile time sin
by skohan 7y ago
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.
- _bxg1 7y ago> since "foo = 5" does not evaluate to a boolean 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.
- skohan 7y agoYeah I know, but there's a wide range of languages which are neither C nor Rust. 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.
- leshow 7y agoOut of curiousity, which languages are you referring to? Assignment in if-statements is possible in C, C++, js, Go, and many other C-like languages. 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.
- skohan 7y agoSwift, Kotlin, D, C# to name a few. Are you sure about Go? I just tried this in an online playground, and I get this error: syntax error: assignment x = 2 used as value