Member-only story
Go Lacks Ternary Operators. Here Are Some Equivalents
Alternatives for the ternary operator in Go
If you were like me, a pure Java developer before writing Go, you must be wondering why Go doesn’t support the ternary operator like return a > 1 ? 0 : 1
.
Most mainstream languages like C and Java are supportive of ternary operators; languages like Python and Ruby support the simplified if-else
one-liner, such as a = 0 if a > 1
. However, Go is not among them. And it is not only about adding operators but also a concept of coding in a more convenient way, such as the ?:
expression can be perfectly replaced by if-else,
but what if you are required to duplicate it dozens or hundred times? You must be seeking the optimizations without hesitation.
if a > 1 {
return 0
else {
return 1
}
No Ternary Operator in Go
As early as 2012, there was a discussion on whether to add ternary operators, which was rejected finally and the answer was added to the FAQ.
The reason
?:
is absent from Go is that the language's designers had seen the operation used too often to create impenetrably complex expressions. Theif-else
form, although longer, is unquestionably clearer. A language needs only one conditional control flow construct.