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

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?