Golang是否有与Python中的短路习惯用法`z = x or y`等效的语法?

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

Does golang have the equivalent of this Python short circuit idiom `z = x or y`

问题

在Python中,z = x or y可以理解为将z赋值为如果x为假值,则为y,否则为x,在golang中是否有类似的习惯用法?

具体来说,右侧的两个变量是字符串,如果第一个变量非空,则将其赋值给z,否则将第二个变量赋值给z。

英文:

In Python z = x or y can be understood as assign z as if x is falsey, then y, else x, is there a similar idiom in golang?

Specifically the two variables on the right are strings, I'd like to assign the first if it's non-emtpy, otherwise the second.

答案1

得分: 4

不,你必须使用if/else:

s1, s2 := "", "hello"
var x string

if s1 == "" {
    x = s2
} else {
    x = s1
}
英文:

No, you have to use if/else:

s1, s2 := "", "hello"
var x string

if s1 == "" {
	x = s2
} else {
	x = s1
}

huangapple
  • 本文由 发表于 2015年12月8日 06:32:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/34144571.html
匿名

发表评论

匿名网友

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

确定