What is the idiomatic Go equivalent of C's ternary operator?
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 :
int index = val > 0 ? val : -val
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
var index int
if val > 0 {
index = val
} else {
index = -val
}
Is there something better ?
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
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.
没有Go没有三元运算符,使用if / else语法是惯用的方式:http://golang.org/doc/faq#Does_Go_have_a_ternary_form
Suppose you have the following ternary expression (in C):
int a = test ? 1 : 2;
The idiomatic approach in Go would be to simply use an if
block:
var a int
if test {
a = 1
} else {
a = 2
}
However, that might not fit your requirements. In my case, I needed an inline expression for a code generation template.
I used an immediately evaluated anonymous function:
a := func() int { if test { return 1 } else { return 2 } }()
This ensures that both branches are not evaluated as well.
链接地址: http://www.djcxy.com/p/7418.html上一篇: 函数式编程是否取代GoF设计模式?
下一篇: C的三元运算符的惯用的Go等价物是什么?