如何根据操作系统设置变量

Kyl*_*ndt 2 build go

我知道我可以命名特定的文件_windows.go,_linux.go等,这将使它们只为该特定的操作系统编译.

在文件名中没有指定go os的文件中,有没有办法根据go os在文件中设置变量和/或常量?也许在案例陈述中?

Not*_*fer 7

runtime.GOOS是你的朋友.但是,请记住,您不能基于它设置常量(尽管您可以将其复制到您自己的常量) - 仅限变量,并且仅在运行时.您可以使用init()模块中的函数在程序启动时自动运行检测.

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)
}
Run Code Online (Sandbox Code Playgroud)