duanchifo2866 2013-11-07 22:02 采纳率: 100%
浏览 40
已采纳

如何在Go中可靠地检测OS /平台

Here's what I'm currently using, which I think gets the job done, but there's got to be a better way:

func isWindows() bool {
    return os.PathSeparator == '\\' && os.PathListSeparator == ';'
}

As you can see, in my case all I need to know is how to detect windows but I'd like to know the way to detect any platform/os.

Play:

http://play.golang.org/p/r4lYWDJDxL

  • 写回答

2条回答 默认 最新

  • dongmi9494 2013-11-07 22:19
    关注

    Detection at compile time

    If you're doing this to have different implementations depending on the OS, it is more useful to have separate files with the implementation of that feature and add build tags to each of the files. This is used in many places in the standard library, for example in the os package.

    These so called 'Build constraints' or 'Build tags' are explained here.

    Say you have the constant PATH_SEPARATOR and you want that platform dependant, you would make two files, one for windows and one for the (unix) rest:

    /project/path_windows.go
    /project/path_unix.go
    

    The code of these files would then be:

    path_windows.go

    // +build windows
    
    package project
    
    const PATH_SEPARATOR = '\\'
    

    path_unix.go

    // +build !windows
    
    package project
    
    const PATH_SEPARATOR = '/'
    

    You can now access PATH_SEPARATOR in your code and have it platform dependant.

    Detection at runtime

    If you want to determine the operating system at runtime, use the runtime.GOOS variable:

    if runtime.GOOS == "windows" {
        fmt.Println("Hello from Windows")
    }
    

    While this is compiled into the runtime and therefore ignores the environment, you can nevertheless be relatively certain that the value is correct. The reason for this is that every platform that is worth distinguishing needs rebuilding due to different executable formats and thus has a new GOOS value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误