Member-only story

Go Lacks Ternary Operators. Here Are Some Equivalents

Stefanie Lai
Better Programming
Published in
5 min readNov 14, 2022

--

From Unsplash donio3d

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. The if-else form, although longer, is unquestionably clearer. A language needs only one conditional control flow construct.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

--

--

Write a response