Ternary operator in Golang

In this article, you will learn about the ternary operator in the Go language.

What Is a Ternary Operator?

As mentioned, a ternary operator allows you to perform an if-else block with minimal code and a single-line statement.

In languages that support it, a ternary operator’s syntax is as shown:

a = b > 0 ? 1:0

The previous code can be interpreted as:

If b is greater than 0, then a is 1 else a is 0.

Is there any ternary operator in Golang?

There is no ternary testing operation in Go. You may use the following to achieve the same result:

if expr {
    n = trueVal
} else {
    n = falseVal
}

Why there’s no ternary operator in Golang?

The reason ?: is absent from Go is that the language’s designers had seen the operation used too often to create impenetrably complex expressions. The if-else form, although longer, is unquestionably clearer. A language needs only one conditional control flow construct.

How to perform ternary operations in Golang alternatively?

You can implement an if-else block instead of using the ternary operator as it is absent in the Go language. It is much cleaner and easy to understand. Let’s see the above example of the ternary operator in the Go language by using an if-else statement.

package main

import (
        "fmt"
)

func main() {

        var x, y, result int
                x = 5
                y = 10

        if x > y {
                result = x
        } else {
                result = y
        }

        fmt.Println(result)
}

// Output : 10

You have to write more code than ternary operator. But it is the design choice of Go creators. One of the main reasons behind it is to avoid complexity of the code and apply a cleaner and understandable standard of code.

Answer #3:

As pointed out (and hopefully unsurprisingly), using if+else is indeed the idiomatic way to do conditionals in Go.

In addition to the full blown var+if+else block of code, though, this spelling is also used often:

index := val
if val <= 0 {
    index = -val
}

and if you have a block of code that is repetitive enough, such as the equivalent of int value = a <= b ? a : b, you can create a function to hold it:

func min(a, b int) int {
    if a <= b {
        return a
    }
    return b
}

...

value := min(a, b)

The compiler will inline such simple functions, so it’s fast, more clear, and shorter.

Answer #4:

One-liners, though shunned by the creators, have their place.

This one solves the lazy evaluation problem by letting you, optionally, pass functions to be evaluated if necessary:

func FullTernary(e bool, a, b interface{}) interface{} {
    if e {
        if reflect.TypeOf(a).Kind() == reflect.Func {
            return a.(func() interface{})()
        }
        return a
    }
    if reflect.TypeOf(b).Kind() == reflect.Func {
        return b.(func() interface{})()
    }
    return b
}

func demo() {
    a := "hello"
    b := func() interface{} { return a + " world" }
    c := func() interface{} { return func() string { return "bye" } }
    fmt.Println(FullTernary(true, a, b).(string)) // cast shown, but not required
    fmt.Println(FullTernary(false, a, b))
    fmt.Println(FullTernary(true, b, a))
    fmt.Println(FullTernary(false, b, a))
    fmt.Println(FullTernary(true, c, nil).(func() string)())
}

Output

hello
hello world
hello world
hello
bye
  • Functions passed in must return an interface{} to satisfy the internal cast operation.
  • Depending on the context, you might choose to cast the output to a specific type.
  • If you wanted to return a function from this, you would need to wrap it as shown with c.

Ternary operator in Golang

Suppose you have the following ternary expression (in C):

int a = test ? 1 : 2;

The idiomatic approach in Go would be to simply use an if block:

var a int

if test {
  a = 1
} else {
  a = 2
}

However, that might not fit your requirements. In my case, I needed an inline expression for a code generation template.

I used an immediately evaluated anonymous function:

a := func() int { if test { return 1 } else { return 2 } }()

This ensures that both branches are not evaluated as well.

Hope you learned something from this post.

Follow Programming Articles for more!

About ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ

Linux and Python enthusiast, in love with open source since 2014, Writer at programming-articles.com, India.

View all posts by ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ →