golang

Learn about Ternary operator in Golang


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

A ternary operator is a kind of operator that takes three operands and helps programmers to make decisions. It is a shorter form of if else conditional statement. As it takes three operators, it is called the ternary operator. An example of ternary operator is shown below:

int x = 5, y = 10, result;

result = (x > y) ? x : y;

printf("%d", result);

// Output: 10

This ternary operator is exists in the most programming languages but it is a matter of fact that it is absent in Go language. The reason behind it is very simple. Though ternary operator is very useful to use if one understand it properly, it becomes confusing for those who are new to code. To make things simple Go language prefers the longer version of ternary operator that is if-else which is more readable and easy to implement

Note: This example is given in C language because of non existence of ternary operator in Go.

You can implement if-else block instead of using ternary operator as it is absent in Go language. It is much cleaner and easy to understand. Let’s see the above example of ternary operator in Go language by using 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.


Share on social media

//