runtime.GOOS case

924 views
Skip to first unread message

Eric Brown

unread,
Aug 7, 2017, 5:00:24 PM8/7/17
to golang-nuts
This may be a completely stupid or trivial question; however...

I currently use this on some old code I'm working on and trying to clean things up:

switch os := strings.ToLower(runtime.GOOS); os {
case "windows":
// do windows stuff here
case "linux":
// do linux stuff here
default:
// do default stuff here
}

I hate to import the entire strings package just to ensure that switch will work.  Does anybody know if runtime.GOOS will always return a lowercase value so I don't have to import the strings package just for this single check?  All I can find is that GOOS returns (sys.GOOS)...
I'd rather be safe than sorry.

Chris Manghane

unread,
Aug 7, 2017, 5:11:31 PM8/7/17
to Eric Brown, golang-nuts
You can see how the different runtime.GOOS values are defined in the OS-specific runtime files like https://github.com/golang/go/blob/master/src/runtime/internal/sys/zgoos_windows.go. They happen to be lowercase, but I don't know anything that guarantees that in any future.

Curious though, why does it matter if you import the strings package for a single check? That's surprising to me.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

James Bardin

unread,
Aug 7, 2017, 5:12:03 PM8/7/17
to golang-nuts
They will always be lowercase, as the values are all defined in the code

const GOOS = `android`
const GOOS = `darwin`
const GOOS = `dragonfly`
const GOOS = `freebsd`
const GOOS = `linux`
const GOOS = `nacl`
const GOOS = `netbsd`
const GOOS = `openbsd`
const GOOS = `plan9`
const GOOS = `solaris`
const GOOS = `windows`

But it's usually better to rely on build constraints rather than conditionals at runtime. 

Dave Cheney

unread,
Aug 7, 2017, 5:14:24 PM8/7/17
to golang-nuts
the GOOS values are case sensitive and currently all specified to be lower case; GOOS=linux != GOOS=Linux. You don't need to ToLower a runtime.GOOS as

a. that would mean your Go installation was built with the wrong value
b. by working around this it would hide the problem until it was harder to fix.

Eric Brown

unread,
Aug 7, 2017, 5:15:36 PM8/7/17
to golang-nuts
Appreciate the reply, guys.  Also, Chris, it's not usually a problem... I just prefer to keep the compiled file size and resources minimal; therefore, don't like to import packages unless absolutely necessary.
Reply all
Reply to author
Forward
0 new messages