且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是 C 的三元运算符的惯用 Go 等价物?

更新时间:2023-10-21 09:10:16

正如所指出的(希望不出所料),使用 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.