C的三元运算符的惯用的Go等价物是什么? [英] What is the idiomatic Go equivalent of C's ternary operator?
问题描述
int index = val> 0? val:-val
Go没有条件运算符。实现与上面相同的一段代码的最习惯的方式是什么?我来到了以下解决方案,但它看起来很冗长
var index int
如果val> ; 0 {
index = val
} else {
index = -val
}
有没有更好的方法?
正如指出的那样(希望不出所料) c $ c> if + else 确实是习惯用法在Go中执行条件。 / p>
除了完整的 var + if + else
代码块之外,这种拼写也经常被使用:
index:= val
如果val <= 0 {
index = -val
$ / code>
如果您有足够重复的代码块,例如相当于 int value = a< = b? a:b
,您可以创建一个函数来保存它:
func min(a,b int)int {
如果a< = b {
返回a
}
返回b
}
...
value:= min(a,b)
编译器会内联这么简单功能,所以它更快,更清晰,更短。
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
, 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.
这篇关于C的三元运算符的惯用的Go等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!