The ternary operator in GoLang

In most of the programming languages, there is an operator (?:) called ternary operator which evaluates like an if-else chain will do. But, Go does not have a ternary operator. In this post, we will dive into why it is absent in Go.

What is the ternary operator?

The ternary operator is the ?: operator used for the conditional value. Here is an example of how one would use it in code.

v = f > 0 ? 1 : 0     // if f > 0 then v is 1 else v is 0

This operator is absent in GoLang.

Why is it absent in Go?

The reason is a simple design choice. The operator although once understood, is an easy one is in fact a complicated construct for someone who is new to code. The Go programming language chose the simple approach of if-else. This is a longer version of the operator, but it is more readable.

The solution

The solution is obviously an if-else block. It represents the same code in a much cleaner way. Here is a simple if-else block representing the above expression.

if f > 0 {
        v = 1
} else {
        v = 0
}

The solution is verbose but it is a design choice made by the Go creators. One of the reasons being overuse and abuse of that operator to create extremely complex code that is hard to read. This decision improves over it and forces a cleaner and readable approach over that.