What is the idiomatic Go equivalent of C's ternary operator?
Solution 1:
As pointed out (and hopefully unsurprisingly), using if+else
is indeed the idiomatic way to do conditionals in Go.
In addition to the full blown var+if+else
block of code, though, this spelling is also used often:
index := val
if val <= 0 {
index = -val
}
and if you have a block of code that is repetitive enough, such as the equivalent of int value = a <= b ? a : b
, you can create a function to hold it:
func min(a, b int) int {
if a <= b {
return a
}
return b
}
...
value := min(a, b)
The compiler will inline such simple functions, so it's fast, more clear, and shorter.
Solution 2:
No Go doesn't have a ternary operator, using if/else syntax is the idiomatic way.
Why does Go not have the ?: operator?
There is no ternary testing operation in Go. You may use the following to achieve the same result:
if expr { n = trueVal } else { n = falseVal }
The reason
?:
is absent from Go is that the language's designers had seen the operation used too often to create impenetrably complex expressions. Theif-else
form, although longer, is unquestionably clearer. A language needs only one conditional control flow construct.— Frequently Asked Questions (FAQ) - The Go Programming Language