dpda53918 2013-11-14 13:39
浏览 64
已采纳

C的三元运算符的惯用Go等效项是什么?

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题