golang

Golang Ternary

I am confident that most of us are not new to programming, and if you are, chances of you knowing about the ternary operator are high.

A ternary operator, available in some programming languages, allows a single line to evaluate an if-else block.

Unfortunately, Go does not have a ternary operator.

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

Yes, I agree. It is a very complicated method of writing readable code.

Why Is There No Ternary in Go Programs?

You may ask, why is there a no ternary operator in Go programs? The simple answer is, it’s a design choice.

Although the ternary operator is a very fancy method of writing code, it can be very daunting and challenging to grasp, especially for new programmers. Since Go prides itself as a simple and heavily readable language, it implements an if-else construct instead.

Alternative Option

Ok, so there is no ternary operator in Go. Does that mean we all stop using the language? No. Go programming provides you with an if-else construct to implement a ternary operator. It is much more readable but contains more lines of code.

The following shows how to create a ternary operator:

ifb>0 {
a = 1
} else {
a = 0
}

Conclusion

This article discusses the definition and nature of a ternary operator and why it is not implemented in the Go programming language. We also cover a simple syntax of creating a ternary operator in the Go programming language. We hope you found this article helpful. Check other Linux Hint articles for more tips and tutorials.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list