Go Lacks Ternary Operators. Here Are Some Equivalents | by Stefanie Lai | Nov, 2022

Go. Option for Ternary Operator in

Unsplash. From donio3d

If you were a pure Java developer like me before writing Go, you might be wondering why Go doesn’t support the ternary operator. return a > 1 ? 0 : 1,

Most mainstream languages ​​such as C and Java support ternary operators; Languages ​​like Python and Ruby support Simplify if-else one-liners, such as a = 0 if a > 1, However, Go is not among them. And it’s not only about adding operators, but also the concept of coding in a more convenient way, such as ?: The expression can be completely replaced by if-else, But what if you need to duplicate it dozens or even a hundred times? You must be looking for customization without hesitation.

if a > 1 {
return 0
else
return 1

In early 2012, there was a argument whether to add ternary operators, which was eventually discarded and Answer Added to the FAQ.

the reason ?: Absent from Go, is that the language’s designers saw the operation as frequently used to create impenetrably complex expressions. if-else The form, though tall, is undeniably clear. A language requires only one conditional control flow construct.

This answer does not satisfy everyone, and there are still proposals (offer in 2017) in a request to get it in github issues. Personally, I have a guarded attitude towards the Go team’s approach and want to “beat” their reasons one by one.

Reason 1: Clarity

if-else Can accomplish tasks, but the trade-off is “sacrificing” my keyboard and fingers. For example, using if-else Instead ?: In the previous case it means I tap the keyboard at least 13 more times ( if + else + { + + + return), the number can grow rapidly in a production project.

The ternary operator can be used not only in return, and variable assignment, but can also be used in function parameters, printf parameters, etc. We can see a clear duplicate code if we are changing if-elseIn printf case below.

printf("I’m %s 21 years old, so I %s drink", age > 21 ? "above":"below", age > 21 ? "can" : "cannot") 
// if - else, duplicated code
if age > 21
printf("I’m above 21 years old, so I can drink")
else
printf("I’m below 21 years old, so I can drink")

In general, duplicate code is a bad smell that reduces the readability of the code, even if we encapsulate an additional function to reduce duplicate code. Looking only at the print method, the whole logic falls to pieces.​

if age > 21 {
print("above", "can")
else
print("below", "cannot")

// wrap function
func print(a string, b string)
printf("I’m %s 21 years old, so I %b drink", a, b)
​​

if-else is a change, where the initialization variable is used instead of else, changing the above example to the following. It is more concise, but loses immutability and still results in less readability.

b := 0
if a <= 1
b = 1

return b​

Reason 2: legibility

Validity is a very reasoned concept. At least, I think the readability of return a > 1 ? 0:1 not weaker than if-else, But I can’t tell if there is bias based on my years of Java experience. And from the various comments on the proposal, I think the Go official considers poor readability due to misuse of the ternary operator, and not by the ternary operator, such as multi-level nested expressions. a = b > 100 ? 99 : ( b > 1000 ? 999 : (b > 10000 ? 9999 : ( b > 100000 ? 99999 : …. )))). convert it if-else Makes it more understandable.

if b > 100 {
a = 99
else if b > 1000 {
a = 999
else if b > 10000 {
a = 9999
....​

However, it is not enough to say no to an operator that brings efficiency as it is prone to misuse.

Reason 3: Not all languages ​​support the ternary operator

Besides Go, there are some other languages ​​that don’t support ternary operators, such as Rust, whose team cites a reason as well.

Rust tries to avoid having multiple ways of doing the same thing. Other than this, : The symbol is already more overloaded than I would like, and the classic ternary syntax would be grammatically ambiguous with the already accepted type inscription RFC. Also, there are vague plans to use ? Symbol for future language-level error-handling support.​

But they also mention their future plans ? And : operators, right?

Go users are still working tirelessly to propose other similar optimizations to simplify if-else After the ternary operator fails.

offer Conditional-assign (?=) to limited ternary operator functionality expected to be implemented ?= to complete a line if-else and variable assignment, like a ?= a > 1, 0, 1, This motion also did not pass.

offer Support inline “if” statement syntaxwhich expects to be a one-liner if-else As Python and Ruby, it was also rejected due to insufficient attention and support.

As seen, the Go team probably won’t consider adding the ternary operator, no matter how many times they are asked. Turning to alternatives is the only way out in the short term.

IDE Template

We can create templates with the IDE to ease code generation and avoid duplicates if-else, For example, we can create a live template named tern in IntelliJ.

then we can use turn where if-else required, and enter the relevant expression in the three variables.

generic ternary operator

there is a better solution stack OverflowProvided by a user, which supports the implementation of generics.

func If[T any](cond bool, vtrue, vfalse T) T 
if cond
return vtrue

return vfalse

Then we can convert the previous example to return If(a > 1, 0, 1) Just as easy as the ternary operator. try it yourself Here, I

I enjoy the convenience brought by the ternary operator, however, the Go team is firm on not adding it, although there are always proposals. And before Go executives really change their mind, we can count on other methods to improve our coding efficiency.

Thanks for reading!

https://github.com/golang/go/issues/33171I

I

Leave a Reply