Reputation: 1851
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?
Upvotes: 1
Views: 664
Reputation: 6749
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
}
Upvotes: 0
Reputation:
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
Upvotes: 2