Go Q & A

 

Does Go have a ternary conditional operator?

No, Go does not have a ternary conditional operator like some other programming languages such as C, C++, Java, and JavaScript. In those languages, the ternary conditional operator, often denoted as condition ? expr1 : expr2, allows for concise conditional expressions that return different values based on a condition.

 

However, in Go, the designers opted to exclude the ternary conditional operator for the sake of simplicity and clarity. Instead, Go encourages the use of the traditional if-else statement for conditional logic, which is explicit and easy to understand.

 

Here’s an example of conditional logic using the if-else statement in Go:

go

package main

import (
    "fmt"
)

func main() {
    age := 20

    var message string
    if age >= 18 {
        message = "You are an adult"
    } else {
        message = "You are a minor"
    }

    fmt.Println(message)
}

Output:

sql

You are an adult

 

While the absence of a ternary conditional operator may require a few extra lines of code for conditional expressions in Go, it contributes to the language’s readability, simplicity, and maintainability. By favoring explicitness and clarity over conciseness, Go aims to minimize ambiguity and make code easier to understand for developers of all skill levels.

Previously at
Flag Argentina
Mexico
time icon
GMT-6
Over 5 years of experience in Golang. Led the design and implementation of a distributed system and platform for building conversational chatbots.