Cookies management by TermsFeed Cookie Consent
Russia has invaded Ukraine and already killed tens of thousands of civilians, with many more raped or tortured. It's a genocide. We need your help. Let's fight back against the Russian regime.
Help Ukraine! Fight the Russian regime!

🦥 Ternary operator in Go

introduction syntax

Please consider supporting us by disabling your ad blocker

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



➰ Foreach or for range loop in Go

Learn how to construct the popular programming loop
introduction loop syntax

🎲 Generate a random string in Go

Learn how to generate a random string of a fixed length
introduction random strings

🐤 Create a new file in Go

shorts introduction file