Go: proposal: os: add function to return environment var with default value

Created on 19 Nov 2019  ·  5Comments  ·  Source: golang/go

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

FrozenDueToAge Proposal Proposal-FinalCommentPeriod

Most helpful comment

// 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.

All 5 comments

// 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.

Was this page helpful?
0 / 5 - 0 ratings