golang版本的Ruby的或等于(or-equals)||=。

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

golang version of ruby's or-equals ||=

问题

好的,以下是翻译好的内容:

出于好奇,如果在Go语言中要为变量赋值,而该变量为nil,那么惯用的方式是什么?

我在寻找类似于Ruby中的foo ||= bar的方式。

是否有更简短的版本?

if foo == nil {
  foo = bar
}
英文:

Out of curiosity, what would be the idiomatic way to assign a variable if it's nil in go?

I'm looking for something similar to ruby's foo ||= bar

Is there a shorter version of this?

if foo == nil{  
  foo = bar
}

答案1

得分: 6

你的版本已经是最简单、最短和最符合习惯用法的方法了。

英文:

Your version is already the simplest, shortest and idiomatic way to do it.

huangapple
  • 本文由 发表于 2016年12月7日 05:38:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/41005398.html
匿名

发表评论

匿名网友

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

确定