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 c51单片机控制步进电机
  • ¥20 Visual studio无法检测到设备
  • ¥15 为什么我通过html绘制的SVG折线图插入到word中坐标轴不显示出来
  • ¥30 vue 页面窗口放大或者缩小元素会变化
  • ¥15 questasim仿真报错
  • ¥15 寻找电脑攻防的导师,有问题请教一下。
  • ¥20 微信同是win11,我的电脑安装不了pageoffice,一直无法打开
  • ¥15 这个界面我通过postman请求不到,但是通过浏览器可以正常访问
  • ¥15 多目标优化算法在与其他算法数据对比结果判断
  • ¥15 CPTN和EAST,主干网络是VGG16,请问在ICDAR2015数据集上训练之后,CPTN和EAST模型的大小为多少