4 ms·
The reason it doesn't work is because of how semicolons work: like in C every statement needs to end in a semicolon, but the compiler will automatically insert
by Beltalowda 4y ago
The reason it doesn't work is because of how semicolons work: like in C every statement needs to end in a semicolon, but the compiler will automatically insert them if the last word in a line is a keyword (continue etc.), an identifier, literal value (int, string, etc.), or ++, --, ), ], }. [1]
So your example gets transformed to:
if (cond) { return x };
else { return y };
So it is mentioned in the language specification, just as a non-obvious consequence of this.
It's not my most favourite part of the language either, but at least the compiler message on it is better now (it used to complain about semicolons, which was confusing because they're not there in your source code; now it just says "unexpected else, expecting }", which is still a bit confusing but better).
I'm fairly sure The Go Programming Language book mentions this somewhere near the beginning, but some of the online tutorial/tour perhaps could be improved. There's always a bit of a balance in how much to mention.
[1]: https://go.dev/ref/spec#Semicolons https://go.dev/ref/spec#Semicolons