Cookies management by TermsFeed Cookie Consent

🦥 Ternary operator in Go

introduction syntax

In short, the ternary operator known from languages like PHP or JavaScript is not available in Go. But you can express the same condition using the if {..} else {..} block, which is longer but easier to understand. The fact that it is not in the syntax is the result of a deliberate choice by the language designers, who noticed that the ternary operator is often used to create overly complicated expressions.

As a result, there is only one conditional control flow construct in Go: if {..} else {..}. So, instead of writing:

// this is not available in Go!
variable := <condition> ? <expressionIfTrue> : <expressionIfFalse>

you need to write:

var variable int
if <condition> {
    variable = <expressionIfTrue>
} else {
    variable = <expressionIfFalse>


x := 12
var points int
if x > 10 {
    points = 100
} else {
    points = 0



Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

❤️‍🩹 Recover function in Go

Learn what it is for and how to use the built-in recover() function
introduction syntax builtin

➰ Foreach loop in Go

Learn how to construct the popular programming loop
introduction loop syntax

🫘 Count the occurrences of an element in a slice in Go

Learn how to count elements in a slice that meet certain conditions
introduction generics generics-intro