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

标签 build go

我知道我可以将特定的 go 文件命名为 _windows.go、_linux.go 等,这将使它们只针对该特定操作系统进行编译。

在文件名中没有指定 go 操作系统的文件中,有没有一种方法可以根据 go 操作系统在文件中设置变量和/或常量?也许在案例陈述中?

最佳答案

runtime.GOOS 是你的 friend 。但是,请记住,您不能基于它设置常量(尽管您可以将其复制到您自己的常量中)——只能是变量,而且只能在运行时使用。您可以在模块中使用 init() 函数在程序启动时自动运行检测。

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

关于build - 如何根据操作系统在 Go 中设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23609948/

相关文章:

ios - 带有 Expo 的独立应用程序 iOS 尺寸太大 (218mb)

go - 如何使用 Gorilla Mux 在 GET 请求中进行可选查询?

github - 在 GitHub 安装带有 'go get' 的 Go 包是否算作克隆?

ruby - Rust 数学错误

performance - 加速 Android Studio 构建

java - 如何使用 ant 构建 jar 文件?

c++ - 使 visual studio 项目可移植,问题

iphone - 连接到一台 Mac 的多个 iPhone OS 设备 - 如何选择构建

templates - Go模板无法与if和range一起正常使用

go - 在 Go 中将变量括在方括号中