๐ฆฅ Ternary operator in Go
·1 min
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>
}
Example:
x := 12
var points int
if x > 10 {
points = 100
} else {
points = 0
}
fmt.Println(points)
Output:
100