patterngoCritical
What is the idiomatic Go equivalent of C's ternary operator?
Viewed 0 times
idiomatictheequivalentternaryoperatorwhat
Problem
In C/C++ (and many languages of that family), a common idiom to declare and initialize a variable depending on a condition uses the ternary conditional operator :
Go doesn't have the conditional operator. What is the most idiomatic way to implement the same piece of code as above ? I came to the following solution, but it seems quite verbose
Is there something better ?
int index = val > 0 ? val : -valGo doesn't have the conditional operator. What is the most idiomatic way to implement the same piece of code as above ? I came to the following solution, but it seems quite verbose
var index int
if val > 0 {
index = val
} else {
index = -val
}Is there something better ?
Solution
As pointed out (and hopefully unsurprisingly), using
In addition to the full blown
And if you have a block of code that is repetitive enough, such as the equivalent of
then you can create a function to hold it:
The compiler will inline such simple functions, so it's fast, more clear, and shorter.
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 : bthen 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.
Code Snippets
index := val
if val <= 0 {
index = -val
}func min(a, b int) int {
if a <= b {
return a
}
return b
}
...
value := min(a, b)Context
Stack Overflow Q#19979178, score: 504
Revisions (0)
No revisions yet.