英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论