什么是 C 的三元运算符的惯用 Go 等价物? [英] What is the idiomatic Go equivalent of C's ternary operator?
问题描述
在 C/C++(以及该家族的许多语言)中,根据条件声明和初始化变量的常用习惯用法使用三元条件运算符:
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 没有条件运算符.实现与上面相同的代码段的最惯用的方法是什么?我得出了以下解决方案,但似乎很冗长
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
}
还有更好的吗?
推荐答案
正如所指出的(希望不出所料),使用 if+else
确实是 在 Go 中做条件的惯用方式.
As pointed out (and hopefully unsurprisingly), using if+else
is indeed the idiomatic way to do conditionals in Go.
除了完整的 var+if+else
代码块之外,这种拼写也经常使用:
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
}
并且如果您有足够重复的代码块,例如 int value = a <= b 的等价物?a :b
,你可以创建一个函数来保存它:
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屋!