collinglass
collinglass

Reputation: 830

Go variable declaration from options

I came across this is in node:

var foo = bar || barfoofoo || foooobar;

How could I implement this in go.

Upvotes: 0

Views: 129

Answers (1)

AntoineG
AntoineG

Reputation: 1247

Preamble

I believe this practice is common in Javascript because of the desire to minimize the amount of code that is sent down the pipe. Using short-forms like that, relying on the truthy value of a string, makes it possible to write shorter code and save a couple of bytes.

However, this sort of practice is not type safe and is tricky: it involves expecting from every programmer reading your code that they know the truth value of the types in your language.

I can see an argument for Javascript, but I believe that in most cases you should avoid this form. Something similar is also used in C to verify null values. But unless very idiomatic in the language you use, don't do that. Keep stuff simple-stupid.

To answer your question - how to do this in go.

Here's the trivial implementation: http://play.golang.org/p/EKTP8OsJmR

bar := ""
barfoofoo := ""
foooobar := "omg"

var foo string
if bar != "" {
    foo = bar
} else if barfoofoo != "" {
    foo = barfoofoo
} else {
    foo = foooobar
}

fmt.Printf("foo=%s\n", foo)

Prints foo=omg.

Go is a type safe language. Strings don't have a boolean value, because they are not booleans:

http://play.golang.org/p/r7L8TYvN7c

bar := ""
barfoofoo := ""
foooobar := "omg"

var foo string
if bar {
    foo = bar
} else if barfoofoo {
    foo = barfoofoo
} else {
    foo = foooobar
}

The compiler will yell at you:

prog.go:12: non-bool bar (type string) used as if condition
prog.go:14: non-bool barfoofoo (type string) used as if condition

Otherwise, Go doesn't have a ternary operator, so you can't really do what you're trying:

There is no ternary form in Go. You may use the following to achieve the same result:

if expr {
    n = trueVal
} else {
    n = falseVal
}

Overall, you shouldn't do that, and you can't do that.

Upvotes: 5

Related Questions