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.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.