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.

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

In this example, we defined an anonymous function that checks if a is greater than b.

If it is, the function returns a; otherwise, it returns b. We immediately invoked the anonymous function with (), which makes it similar to a ternary operator regarding readability.

This approach is less idiomatic in Go, and it’s generally recommended to use a regular if-else statement for better readability.

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.

Leave a Comment