Go 语言的环境配置与 Hello world

Published at:
Updated at:
Tags: Go

这只是一个简单的示例,个别细节没做太多解释,可去官网或其他网站自行了解。

示例系统

  • Windows 10

安装 Go 语言开发工具

根据自己的喜好在以下两个链接中,选择其中一个来下载 Go 语言开发工具,选择下载以.msi作为后缀名的 Windows 版。

检查 Go 语言开发工具是否可用

在命令行中直接输入Go命令,如果显示出如以下的提示,说明 Go 语言开发工具已经安装成功。

> go

Go is a tool for managing Go source code.

Usage:

        go <command> [arguments]

The commands are:

        bug         start a bug report
        build       compile packages and dependencies
        clean       remove object files and cached files
        doc         show documentation for package or symbol
        env         print Go environment information
        fix         update packages to use new APIs
        fmt         gofmt (reformat) package sources
        generate    generate Go files by processing source
        get         add dependencies to current module and install them
        install     compile and install packages and dependencies
        list        list packages or modules
        mod         module maintenance
        run         compile and run Go program
        test        test packages
        tool        run specified go tool
        version     print Go version
        vet         report likely mistakes in packages

安装编辑器

在这个示例中我们使用 VS Code 作为 Go 语言的编辑器。

安装 VS Code

安装 VS Code 插件

打开 VS Code,选择左侧的 Extensions,查找并安装以下两个用于中文化Go 语言的插件。

  • Chinese (Simplified) Language Pack for Visual Studio Code
  • Go

安装/更新工具

配置代理

因为国内网络较为特殊的原因,需要配置代理才能通过网络安装/更新工具。

在命令行中输入以下命令配置代理。

> go env -w GO111MODULE=on
> go env -w GPROXY=https://goproxy.cn,direct

在 VS Code 中使用按Ctrl+Shift+P,在打开的输入框中输入Go,这时就可以看到名为Go: Install/Update Tools的选项。点击后将列出的所有工具勾上,再点击确认(OK)进行安装。

当 VS Code 自带的命令行出现类似以下的提示,安装项以SUCCEEDED结尾,说明该安装项已经安装成功。

Installing github.com/uudashr/gopkgs/v2/cmd/gopkgs SUCCEEDED
Installing github.com/ramya-rao-a/go-outline SUCCEEDED
Installing github.com/acroca/go-symbols SUCCEEDED
Installing golang.org/x/tools/cmd/guru SUCCEEDED
Installing golang.org/x/tools/cmd/gorename SUCCEEDED
Installing github.com/cweill/gotests/... SUCCEEDED
Installing github.com/fatih/gomodifytags SUCCEEDED
Installing github.com/josharian/impl SUCCEEDED

如果出现了类似以下提示,那就是有安装项安装失败了。

1 tools failed to install.

Hello, world!

新建一个名为 hello-world 的文件夹,并在此文件夹下运行 go mod init {项目名}:

> mkdir hello-world             # 新建名为hello-world文件夹
> cd ./hello-world              # 切换目录到该文件夹下
> go mod init hello-world       # 使用go mod进行初始化

新建一个名为main.go的文件,放入以下代码。

package main

import "fmt"

func main() {
        fmt.Print("Hello, world!")
}

使用命令行进入 main.go 所在的目录,使用以下命令运行我们刚刚编写的 Hello world 程序。

> go run main.go

最后命令行打印出以下内容,说明刚刚编写的 Hello world 程序已经成功运行。

Hello, world!