bug^君 2013-11-14 13:39 采纳率: 25%
浏览 319
已采纳

自成一体的围棋与 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 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 ?

转载于:https://stackoverflow.com/questions/19979178/what-is-the-idiomatic-go-equivalent-of-cs-ternary-operator

  • 写回答

8条回答 默认 最新

  • from.. 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.

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?