dongniaocheng3773 2014-05-12 13:08
浏览 64
已采纳

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

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?

  • 写回答

2条回答 默认 最新

  • duanhao7786 2014-05-12 13:25
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?