How Set a Variable in Go Depending on OS

huangapple go评论90阅读模式
英文:

How Set a Variable in Go Depending on OS

问题

我知道我可以将特定的go文件命名为_windows.go、_linux.go等,这样它们只会为特定的操作系统进行编译。

在没有在文件名中指定go操作系统的文件中,是否有一种方法可以根据go操作系统设置变量和/或常量?也许可以在一个case语句中实现吗?

英文:

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?

答案1

得分: 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": // 这是 playground 显示的内容!
        foo = 4
    default:
        fmt.Println("What os is this?", runtime.GOOS)

    }

    fmt.Println(foo)
}
英文:

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)
}

答案2

得分: 3

请看一下runtime.GOOS

> GOOS 是运行程序的操作系统目标之一:darwin、freebsd、linux等等。

switch runtime.GOOS {
case "linux":
	fmt.Println("Linux")
default:
	fmt.Println(runtime.GOOS)
}
英文:

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)
}

huangapple
  • 本文由 发表于 2014年5月12日 21:08:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/23609948.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定