Question

I'm aware that I can name particular go files _windows.go, _linux.go, etc and that this will make them only compile for that particular operating system.

Within a file that doesn't have the go os specified in the filename, is there a way I can set a variable and/or constant within a file depending on the go os? Maybe in a case statement?

Was it helpful?

Solution

runtime.GOOS is your friend. However, keep in mind that you can't set constants based on it (although you can copy it to your own constant) - only variables, and only in runtime. You can use an init() function in a module to run the detection automatically when the program starts.

package main

import "fmt"
import "runtime"

func main() {

    fmt.Println("this is", runtime.GOOS)

    foo := 1
    switch runtime.GOOS {
    case "linux":
        foo = 2
    case "darwin":
        foo = 3
    case "nacl": //this is what the playground shows!
        foo = 4
    default:
        fmt.Println("What os is this?", runtime.GOOS)

    }

    fmt.Println(foo)
}

OTHER TIPS

Take a look at runtime.GOOS.

GOOS is the running program's operating system target: one of darwin, freebsd, linux, and so on.

switch runtime.GOOS {
case "linux":
    fmt.Println("Linux")
default:
    fmt.Println(runtime.GOOS)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top