Skip to main content
Engineering Notes · August 2014

Go Has No Ternary

Portrait of Komang Artha Yasa, technology leader, two decades building digital platforms across marketplaces, retail, logistics, fintech, and banking.

The ternary operator is common in programming, syntactic sugar for a single control flow. JavaScript has it, Ruby has it, Python has it. Go does not.

You can mimic it through a map-tuple trick:

a := (map[bool]string{true: "its true", false: "its false"})[expression]

It works, but it’s obfuscated and not idiomatic Go. Plain control flow is faster to read and easier to reason about:

var a string
if expression {
    a = "its true"
} else {
    a = "its false"
}

Or, if one branch is the default:

a := "its true"
if !expression {
    a = "its false"
}

Go’s omission isn’t oversight. It’s a constraint that nudges you toward the version your future self can read at a glance.