跳转至

Hello, Go

在Linux/macOS上,使用VScode编写go语言版本的Hello World

Go安装

下载安装包

鉴于网络原因,使用中国站点

Bash
wget https://golang.google.cn/dl/go1.17.2.linux-amd64.tar.gz

解压与建立符号链接

Bash
1
2
3
4
sudo tar -xvf go1.17.2.linux-amd64.tar.gz -C /opt/

echo "export PATH=$PATH:/opt/go/bin" >> ~/.bashrc
echo "export GOPATH=/opt/go" >> ~/.bashrc

测试是否安装成功

Bash
go version

输出如下

Bash
go version go1.17.2 linux/amd64

配置开发环境 vscode

安装go插件

直接搜索go以及code runner,点击安装即可

安装常用go包

配置代理

Bash
export GO111MODULE=on
export GOPROXY=https://goproxy.io

安装如下扩展

go

runner

Bash
go install golang.org/x/tools/gopls@latest  # go language server
go install honnef.co/go/tools/cmd/staticcheck@latest  # go static checker

配置vscode

Ctrl+Shift+P,打开设置的json文件,追加

JSON
1
2
3
4
5
6
7
8
9
{
    "go.autocompleteUnimportedPackages": true,
    "go.useCodeSnippetsOnFunctionSuggest": true,
    "go.useCodeSnippetsOnFunctionSuggestWithoutType": true,
    "go.inferGopath": true,
    "go.gotoSymbol.includeImports": true,
    "go.gotoSymbol.includeGoroot": true,
    "go.formatTool": "gofmt"
}

Hello world

新建go文件

Go
1
2
3
4
5
6
7
package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}

保存后,vscode将自动执行gofmt确保代码风格符合go要求。

运行go文件

点击右上角运行即可

run

参考

  1. Go语言环境安装:https://www.runoob.com/go/go-environment.html
  2. Golang中国下载站:https://golang.google.cn/dl/
  3. 使用GOPROXY环境变量配置代理:https://www.cnblogs.com/sparkdev/p/10649159.html
  4. Linux解压命令:https://www.cnblogs.com/cursorhu/p/5891699.html