我知道我可以将特定的 go 文件命名为 _windows.go、_linux.go 等,这将使它们只针对该特定操作系统进行编译。
在文件名中没有指定 go 操作系统的文件中,有没有一种方法可以根据 go 操作系统在文件中设置变量和/或常量?也许在案例陈述中?
最佳答案
runtime.GOOS
是你的 friend 。但是,请记住,您不能基于它设置常量(尽管您可以将其复制到您自己的常量中)——只能是变量,而且只能在运行时使用。您可以在模块中使用 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)
}
关于build - 如何根据操作系统在 Go 中设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23609948/