dongqian6554 2013-08-04 03:05
浏览 20
已采纳

从选项进行变量声明

I came across this is in node:

var foo = bar || barfoofoo || foooobar;

How could I implement this in go.

  • 写回答

1条回答 默认 最新

  • dongzhuanlei0768 2013-08-04 05:21
    关注

    Preamble

    I believe this practice is common in Javascript because of the desire to minimize the amount of code that is sent down the pipe. Using short-forms like that, relying on the truthy value of a string, makes it possible to write shorter code and save a couple of bytes.

    However, this sort of practice is not type safe and is tricky: it involves expecting from every programmer reading your code that they know the truth value of the types in your language.

    I can see an argument for Javascript, but I believe that in most cases you should avoid this form. Something similar is also used in C to verify null values. But unless very idiomatic in the language you use, don't do that. Keep stuff simple-stupid.

    To answer your question - how to do this in go.

    Here's the trivial implementation: http://play.golang.org/p/EKTP8OsJmR

    bar := ""
    barfoofoo := ""
    foooobar := "omg"
    
    var foo string
    if bar != "" {
        foo = bar
    } else if barfoofoo != "" {
        foo = barfoofoo
    } else {
        foo = foooobar
    }
    
    fmt.Printf("foo=%s
    ", foo)
    

    Prints foo=omg.

    Go is a type safe language. Strings don't have a boolean value, because they are not booleans:

    http://play.golang.org/p/r7L8TYvN7c

    bar := ""
    barfoofoo := ""
    foooobar := "omg"
    
    var foo string
    if bar {
        foo = bar
    } else if barfoofoo {
        foo = barfoofoo
    } else {
        foo = foooobar
    }
    

    The compiler will yell at you:

    prog.go:12: non-bool bar (type string) used as if condition
    prog.go:14: non-bool barfoofoo (type string) used as if condition
    

    Otherwise, Go doesn't have a ternary operator, so you can't really do what you're trying:

    There is no ternary form in Go. You may use the following to achieve the same result:

    if expr {
        n = trueVal
    } else {
        n = falseVal
    }
    

    Overall, you shouldn't do that, and you can't do that.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c