funcmain() { fmt.Print("You are using ", runtime.Compiler, " ") fmt.Println("on a", runtime.GOARCH, "machine") fmt.Println("Using Go version", runtime.Version()) fmt.Println("Number of CPUs:", runtime.NumCPU()) fmt.Println("Number of Goroutines:", runtime.NumGoroutine())}
在装有 Go 1.11.4 的 macOS Mojave 机器上执行goEnv.go将输出:
$ go run goEnv.go
You are using gc on a amd64 machine
Using Go version go1.11.4
Number of CPUs: 8
Number of Goroutines: 1
同样的代码在装有 Go 1.3.3 的 Debian Linux 机器上输出如下:
$ go run goEnv.go
You are using gc on a amd64 machine
Using Go version go1.3.3
Number of CPUs: 1
Number of Goroutines: 4
在名为requiredVersion.go的程序中说明了获取到有关 Go 环境的信息有什么用处,该程序会告诉你是否使用的是 Go1.8 或更高版本:
packagemainimport ("fmt""runtime""strconv""strings")funcmain() { myVersion := runtime.Version() major := strings.Split(myVersion, ".")[0][2] minor := strings.Split(myVersion, ".")[1] m1, _ := strconv.Atoi(string(major)) m2, _ := strconv.Atoi(minor)if m1 ==1&& m2 <8 { fmt.Println("Need Go version 1.8 or higher!")return } fmt.Println("You are using Go version 1.8 or higher!")}
stringsGo 标准包用于拆分从runtime.Version()获得的 Go 版本字符串,以获取其前两个部分,而 strconv.Atoi()函数用于将字符串转换为整数。
在 macOS Mojave 机器上执行requiredVersion.go将输出:
$ go run requiredVersion.go
You are using Go version 1.8 or higher!
但如果你在 Debian Linux 机器上运行requiredVersion.go,它将输出:
$ go run requiredVersion.go
Need Go version 1.8 or higher!
因此,通过调用程序requiredVersion.go,你能够确定 UNIX 计算机是否具有所需的 Go 版本。