Description
Currently, go doesn't support ternary operators. As far as I know, the main argument against it is "People will misuse it, so it will be harder to read code". I don't think this will happen, here's why:
Most developers write their code with the default code conventions. Sometimes they change small things like the tab size or a newline before a {, but overall, it's the same. So who is misusing them? New developers do so. People who started developing are doing many crazy things in their code, but their is one thing most new developers don't do, especially if it's their first language: They don't contribute much to the community, until they are good enough. And if they are, they'll know code conventions.
Take a look at java. How often have you seen java code which is unreadable, because people use ternary operators? I'm developing java since years and I never had this problem when reading code on github, stackoverflow or somewhere else.
I think, ternary operators would make code smaller, while it's still good to read. Here are some examples how they could look like and why they are useful.
Example one
Without:
var test string
testMap, err := getMap()
if err != nil {
test = testMap["test"]
} else {
test = "..."
}
With them (parenthesis are optional, but this looks better with them):
testMap, err := getMap()
test := (err == nil ? testMap["test"] : "...")
They could also be made without a "else". Such a feature was also requested here. Example:
testMap, err := getMap()
test := (err == nil ? testMap["test"])
Example two
Without:
func abs(a int) int {
if a >= 0 {
return a
}
return -a
}
With:
func abs(a int) int {
return a >= 0 ? a : -a
}```
Tell me what you think about it in the answers. 👍