2013-11-14 13:39
浏览 63


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 ?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

7条回答 默认 最新

  • dongshen7407 2013-11-14 14:08

    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.

    解决 无用
    打赏 举报

相关推荐 更多相似问题