Allison Piovani
Posted on October 9, 2022
One things I miss most about Go is Ternary, coming from PHP and Node where the ternary is already well established, I understand how it can be controversial since a lot of them use complex logic in them, that would fit more in IF, Else and Switch. It's like a famous quote form the comics: "With great power comes great responsibility".
The discussion about the Go and Ternary isn't new, there are a lot of issues on the topic, I'll leave her sources for you to delve into, I'll summarize the points that I think are most important on both sides, and the give my personal conclusion.
Benefits
1) Drastucally reduces the use lines code.
var n T
if expr {
n = trueVal
} else {
n = falseVal
}
var n = expr ? trueVal : falseVal
2) If the problem is the sumbols ?
, :
. =
, an approach that not even in python can be quite interesting.
x := "yes" if true else "no"
3) Languages like C and C++, which are the example base of Go, have ternaries.
4) Variable that nedd a value default if no value is assigned to it, for example: service port.
Disadvantages
1) When there is more than one expression to be validated, the ternary operation is difficult to read and it becomes impossible to determine its consummation.
var b1, b2, b3 bool
...
var s = b1 || b2 ? b2 && b3 ? b1 && b3 : "s1" : "s2" : "s3": "s4"
2) Can replaced by operations like IF, ELSE and Switch.
3) Deviates from Go's goal of clarity and simplicity when it comes to syntax.
Conclusion
The ternary will not come to version 1.20 (at this time we are on 1.19), discussions are whether it will come in version 2 of Go, but the reality that will hardly come, the communicates it despite being divided the majority from what I see defends that should still keep the aspects of simplicity in its syntax, even if it requires more lines of code.
The biggest fear of communicating is the creation of more complex codes, I personally prefer autonomy for developers and their teams to choose the best way to write, one more option would be nice, since there are countless that make more sense to use just one line than to use at least 3.
No everything is lost, if it is really necessary there are packages in Go that create the ternaries in Go or leave it very close to what we have in other languages, example: ternary, logically we must have other scattered around Github.
Sources
Posted on October 9, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.