How to use OR operator properly in Golang

huangapple go评论75阅读模式
英文:

How to use OR operator properly in Golang

问题

如何在Golang中简化这个代码:

var planningDate string
date, ok := data["planningDate"]
if !ok {
  planningDate = util.TimeStamp()
} else {
  planningDate = date
}

谢谢。

英文:

How can i do this simplified in Golang

var planningDate string
  date, ok := data["planningDate"]
  if !ok {
    planningDate = util.TimeStamp()
  } else {
    planningDate = date
  }

Thanx

答案1

得分: 3

我在一行代码中没有找到任何方法来实现这个,因为Go语言中没有三元运算符。你也不能使用|,因为操作数不是数字。不过,以下是一个三行代码的解决方案(假设date只是一个临时变量):

planningDate, ok := data["planningDate"]
if !ok {
    planningDate = util.TimeStamp()
}
英文:

I don't see any way to do this in a single line, as there is no ternary operator in Go. You cannot use | either as operands are not numbers. However, here is a solution in three lines (assuming date was just a temporary variable):

planningDate, ok := data["planningDate"]
if !ok {
    planningDate = util.TimeStamp()
}

答案2

得分: 2

你可以这样做:

func T(exp bool, a, b interface{}) interface{} {
    if exp {
        return a
    }
    return b
}

// 在需要的时候可以像三元运算符一样使用它:
planningDate = T(ok, date, util.TimeStamp())

这段代码定义了一个函数 T,它接受一个布尔表达式 exp 和两个接口类型的参数 ab。如果 exp 为真,函数返回 a,否则返回 b。你可以在需要的地方使用这个函数,就像使用三元运算符一样。在你的例子中,planningDate 的值将根据 ok 的值来确定,如果 ok 为真,planningDate 将被赋值为 date,否则将被赋值为 util.TimeStamp()

英文:

You can do something like:

func T(exp bool, a, b interface{}) interface{} {
    if exp {
        return a
    }
    return b
}

and use it whenever you want, like a ternary-operator:

planningDate = T((ok), date, util.TimeStamp())

huangapple
  • 本文由 发表于 2014年7月27日 17:24:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/24979618.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定