> For the complete documentation index, see [llms.txt](https://hantmac.gitbook.io/mastering-go-second/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hantmac.gitbook.io/mastering-go-second/02.0/02.8.md).

# 配置 Go 开发环境

本节将讨论使用`runtime` package 的功能和属性查找有关当前 Go 环境的信息。本节中将程序命名为`goEnv.go`，它将分为两部分。

第一部分：

```go
package main
import (
  "fmt"
  "runtime"
)
```

`runtime` package 包含获取 runtime 信息的函数和属性。 `goEnv.go`的第二个代码部分包含`main()`函数的实现：

```go
func main() {
  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 或更高版本：

```go
package main
import (
  "fmt"
  "runtime"
  "strconv"
  "strings"
)
func main() {
  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!")
}
```

`strings`Go 标准包用于拆分从`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 版本。
