I want to emulate the OR |
operator in Go, when I declare a variable. So return the right handside when the value is not presented:
port := strconv.Itoa(os.Getenv("PORT")) | "8080"
How can I achieve this?
I want to emulate the OR |
operator in Go, when I declare a variable. So return the right handside when the value is not presented:
port := strconv.Itoa(os.Getenv("PORT")) | "8080"
How can I achieve this?
You can't use |
or ||
like this in Go.
|
is an Arithmetic operator and applies only to numeric values and ||
is a Logical operator, and applies only to boolean values.
Go has no concept of "truthy" or "falsy" as in JavaScript; for example if "some_string"
or if 0
are invalid. You'll need to explicitly use a comparison with ==
, >
: if 0 == 0
and if "some_string" == ""
.
Itoa
always returns a String, as does os.GetEnv
, which is documented as returning a string and:
It returns the value, which will be empty if the variable is not present.
"Empty" being an "empty string". In Go, a string is always a string; only a limited set of values such as pointers and error
can be compared to nil
(and primitives like strings can't).
It will never return a number type (e.g. int
), so passing the output of this to Itoa
is always an error.
What you probably want is Atoi
, which returns an error as the second return value:
port, err := strconv.Atoi(os.Getenv("PORT"))
if err != nil {
fmt.Println("unable to get PORT environment variable, falling back to 8080")
// Use =, not :=
// Otherwise it'll create new port variable local to this if block.
// Common mistake for beginners and even experienced programmers.
port = 8080
}
Or:
port := 8080
if os.Getenv("PORT") != "" {
var err error
port, err = strconv.Atoi(os.Getenv("PORT"))
if err != nil {
fmt.Fprintf(os.Stderr, "error: unable to get PORT environment variable: %v
", err)
os.Exit(1)
}
}
If you're thinking "gee, that's verbose compared to my JavaScript one-liner!" then you're correct. In part this is due to the nature of static vs. dynamic languages, and in part this is due to Go's nature of being very explicit and easy-to-read.
But you get type safety and readability in return :-)