下载安装 Go

Go releases 下载安装最新版本 Go,或者直接用 winget 安装:

winget install GoLang.Go

安装完毕后在终端执行 go version 可查看当前 Go 语言版本。

修改 Go 模块代理

开启 Go modules,确保 Go 会从模块代理拉取依赖包。

# 启用 Go modules
go env -w GO111MODULE=on
# 修改 GOPROXY
go env -w GOPROXY=https://goproxy.cn,direct

创建仓库文件夹

仓库文件夹就是写代码的地方,随便找个地方创建个文件夹就行。

初始化主模块

在仓库文件夹下执行以下命令,将创建 Go 主模块的 go.mod 文件:

go mod init main

每个模块都有一个 go.mod 文件,如果没有 go.mod,VSCode 将难以进行代码检查和调试。

以下是一个简单的目录结构展示,“MyFirstGo” 是我随便起的仓库名。main.go 是仓库中主模块下的主包。

/MyFirstGo
├── go.mod
└── main.go

关系总结:仓库→模块→包

安装 VSCode Go 扩展

在 VSCode 中打开仓库文件夹,安装 Go 扩展。

首次安装完成后会出现以下提示:

The “gopls” command is not available. Run “go install -v golang.org/x/tools/gopls@latest” to install.

点 Install。

稍等一会儿,不出意外的话可以看到 VSCode 输出以下内容:

All tools successfully installed. You are ready to Go. :)

安装静态检查工具

如果 VSCode 右下角出现 “Analysis Tools Missing”,点它一下然后 Install 就行。

创建 launch.json

点左侧运行和调试的图标,点“创建 launch.json 文件”。

这时,VSCode 会让你 Choose debug configuration。选第一个“Go: Launch Package”。

在 setting.json 里加上一行 "console": "integratedTerminal"。具体位置参考下面的配置:

{
    // 使用 IntelliSense 了解相关属性。
    // 悬停以查看现有属性的描述。
    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch Package",
            "type": "go",
            "request": "launch",
            "mode": "auto",
            "program": "${fileDirname}",
            "console": "integratedTerminal"
        }
    ]
}

"console": "integratedTerminal" 意为在 VSCode 内置终端中运行 Go 程序。

编写代码

在仓库文件下的 main.go 中随便敲个 Hello world:

package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello world")
}

按 F5,右下角提示要求安装 dlv,直接 Install 即可。

安装完之后再按 F5 调试运行代码,可以看到终端已经输出 Hello world。

开始你的 Go 语言之旅