How to define a variable in Go depending on the operating system
source link: https://www.codesd.com/item/how-to-define-a-variable-in-go-depending-on-the-operating-system.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to define a variable in Go depending on the operating system
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?
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)
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK