What is Ternary Operator in Golang

Go does not have a built-in ternary operator, but you can use a  “short if-else” expression in a single line to simulate a ternary operator.

The absence of the ternary conditional operator (often written as ?: in languages like C, C++, Java, etc.) in Go reflects this philosophy.

Why ternary operator is absent in Go?

Readability: Ternary operators can make code concise but also make it harder to read, especially when nested or used in long expressions. Go prioritizes readability over brevity.

Simplicity: Keeping the language specification simpler can make it easier for newcomers to learn and for developers to keep the entirety of the language in their heads.

Avoid Ambiguity: Ternary operations can sometimes introduce ambiguity in expressions, especially when mixed with other operators. By relying on the more lengthy if-else construct, Go ensures a clear control flow.

Consistency: Go has made other design decisions prioritizing explicitness over brevity, such as requiring braces around if and for blocks, even if they contain only one statement. The absence of the ternary operator is consistent with these choices.

Example 1

package main

import "fmt"

func main() {
  a := 19
  b := 21

  // Simulated ternary operator
  max := func() int { if a > b { return a }; return b }()

  fmt.Println("Max:", max)
}

Output

Max: 21

Example 2

package main

import "fmt"

func main() {
  a := 19
  b := 21

  var max int
  if a > b {
    max = a
  } else {
    max = b
  }

 fmt.Println("Max:", max)
}

Output

Max: 21

In this code, we used a regular “if-else statement” to get the maximum value between a and b and assign it to the max variable.

That’s it!