1、下载
1、国内镜像下载地址:https://golang.google.cn/dl/
2、终端中输入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 download and install packages and dependencies
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
Use "go help <command>" for more information about a command.
Additional help topics:
buildmode build modes
c calling between Go and C
cache build and test caching
environment environment variables
filetype file types
go.mod the go.mod file
gopath GOPATH environment variable
gopath-get legacy GOPATH go get
goproxy module proxy protocol
importpath import path syntax
modules modules, module versions, and more
module-get module-aware go get
packages package lists and patterns
testflag testing flags
testfunc testing functions
Use "go help <topic>" for more information about that topic.
3、开发环境构建:通过go version查看版本,在1.8版本前必须设置这个环境变量。1.8版本后(含1.8)如果没有设置使用默认值
在 Unix 上默认为 $HOME/go
在 Windows 上默认为 %USERPROFILE%/go
在 Mac 上 GOPATH 可以通过修改 ~/.bash_profile 来设置
2、测试是否安装成功
新建源码文件hello.go
cd /Users/wangqian/Desktop/Golang_Study/src //打开源文件存放的位置
vim hello.go // 编辑hello.go文件
编码hello.go文件:
package main
import "fmt"
func main(){
fmt.Printf("hello world\n")
}
退出保存后直接运行
go run hello.go
wangqiandeMacBook-Pro:src wangqian$ go run hello.go
hello world
现在我们把源文件编译成二进制文件,并且运行当前二进制文件
go build -ldflags "-s -w" -o hi.out
wangqiandeMacBook-Pro:src wangqian$ go build -ldflags "-s -w" -o hi.out
wangqiandeMacBook-Pro:src wangqian$ ./hi.out
hello world
这样在当前文件夹中就会存在一个源文件,一个编译文件
3、go常用命令介绍
go run 路径需要完整的路径到src
wangqiandeMacBook-Pro:Golang_Study wangqian$ go run src/day_01/hello_world.go
hello world
wangqiandeMacBook-Pro:Golang_Study wangqian$ go run day_01/hello_world.go
stat day_01/hello_world.go: no such file or directory
go build 编译的时候制定固定的包就行了,不需要带上src
go build day_01 go build 是在当前文件路径生成可执行文件,
go build -o bin/hello2 day_01 指定在bin路径下生成名称hello2的可执行文件
go install day_01 生成可执行文件在bin目录下
前提是go环境bin路径修改过 GOBIN=”/Users/wangqian/Desktop/Golang_Study/bin”
go fmt day_01 格式化代码 直接包名路径就行
在VSCode中目录结构如下图所示:

4、设置GOPATH环境变量
开始写 go 项目代码之前,需要我们先配置好环境变量。编辑 ~/.bash_profile(在终端中运行 vi ~/.bash_profile 即可)来添加下面这行代码(如果你找不到 .bash_profile,那自己创建一个就可以了)
export GOPATH=$HOME/go
保存然后退出你的编辑器。然后在终端中运行下面命令
source ~/.bash_profile
提示:$HOME是每个电脑下的用户主目录,每个电脑可能不同,可以在终端运行 echo $HOME 获取
GOROOT 默认是在 /usr/local/go,如果没有,可以在 bash_profile 文件中设置。
export GOROOT=/usr/local/go
然后保存并退出编辑器,运行 source ~/.bash_profile 命令即可