简体   繁体   中英

How to use OR operator properly in Golang

How can i do this simplified in Golang

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

Thanx

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()
}

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM