在Go语言中有没有这个JS表达式的等价物?

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

Is there an equivalent of this JS expression in Go?

问题

假设我们有两个字符串,str1和str2。我想要一个新的变量str3,如果str1不为空,则等于str1,否则等于str2。

在JavaScript中,我会这样写:

var str3 = str1 || str2;

而在Go语言中,我需要这样写:

str3 := str1
if str1 == "" {
    str3 = str2
}

在我看来,这种写法有点啰嗦。是否有与JavaScript中相同的表达式?

英文:

Let's say we have 2 strings, str1 and str2. I want a new variable str3 to equal str1, or if str1 is empty then equal str2.

In JS I would write:

var str3 = str1 || str2

While in Go I have to do it like:

str3 := str1
if str1 == "" {
    str3 = str2
}

which is a little bit too verbose imo.
Is there an equivalent expression as the one in JS?

答案1

得分: 2

在Go语言中没有与JavaScript中的那个表达式等效的表达式。但是,如果你经常需要这样做,你可以编写一个函数来实现你想要的功能:

func strs(s ...string) string {
    if len(s) == 0 {
        return ""
    }
    for _, str := range s[:len(s)-1] {
        if str != "" {
            return str
        }
    }
    return s[len(s)-1]
}

用法:

str3 := strs(str1, str2)

链接:https://play.golang.org/p/Gl_06XDjW4

英文:

> Is there an equivalent expression as the one in JS?

No, but if you find yourself doing this often, you could write a function that does what you're trying to accomplish:

func strs(s ...string) string {
	if len(s) == 0 {
		return ""
	}
	for _, str := range s[:len(s)-1] {
		if str != "" {
			return str
		}
	}
	return s[len(s)-1]
}

Usage:

str3 := strs(str1, str2)

https://play.golang.org/p/Gl_06XDjW4

答案2

得分: 0

在Go语言中没有等效的操作。你需要使用if语句(或者switch语句,但那样会更冗长)。我会这样写:

var str3 string
if str1 != "" {
    str3 = str1
} else {
    str3 = str2
}
英文:

There is no equivalent operation in Go. You have to do it with an if (or a switch, but that's even more verbose). I would write it like this:

var str3 string
if str1 != "" {
    str3 = str1
} else {
    str3 = str2
}

huangapple
  • 本文由 发表于 2016年4月4日 04:54:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/36391058.html
匿名

发表评论

匿名网友

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

确定