Adding a very small QoL function to go giving the ability to return an environment variable with a possible fallback in one line
Since go doesn't support Overloading or Optional parameters (as far as I am aware)
I am proposing to add
os.GetEnvWithDefault(envname, defaultvalue)
the added benefit is this way it's also a non-breaking change
// use the default if empty
val := os.Getenv(name)
if val == "" {
val = default
}
// use the default if not set
val, ok := os.LookupEnv(name)
if !ok {
val = default
}
Which of the two do you mean? Either seems reasonable, and I don't think there's a clear winner.
I think it's best to let the developer write another three lines and make it explicit and simple. If you want to avoid the extra typing, just set up an editor macro or copy-paste.
I would personally go with
val, ok := syscall.Getenv(key)
if !ok {
val=default
}
because this is technically how lookupenv works. If you look at the env.go they don't look too different from each other too much
@timoheijne You missed or at least did not respond to the semantic difference that @mvdan was pointing out. Some programs will want to distinguish unset from empty; others will not. That's why both os.Getenv and os.LookupEnv exist. If you want to also set a default in one case or the other, it seems reasonable to ask the developer to write out which matters, explicitly.
@mvdan:
I think it's best to let the developer write another three lines and make it explicit and simple. If you want to avoid the extra typing, just set up an editor macro or copy-paste.
Or, you know, write a function. :-)
Given the semantic subtleties and how easy it is to write the function you want, this seems like a likely decline.
Leaving open for a week for final comments.
No change in consensus, so declining.
Most helpful comment
Which of the two do you mean? Either seems reasonable, and I don't think there's a clear winner.
I think it's best to let the developer write another three lines and make it explicit and simple. If you want to avoid the extra typing, just set up an editor macro or copy-paste.