安装(Linux 环境)
按以下命令安装:
# 下载安装包
wget https://go.dev/dl/go1.17.5.linux-amd64.tar.gz
# 解压
rm -rf /usr/local/go && tar -C /usr/local -xzf go1.17.5.linux-amd64.tar.gz
# 设置环境变量
export PATH=$PATH:/usr/local/go/bin
检查是否安装成功,输出版本后表示安装成功。
$ go version
go version go1.17.5 linux/amd64
写 hello world
创建项目:
cd && mkdir hello && cd hello
初始化依赖:
$ go mod init example/hello
go: creating new go.mod: module example/hello
创建 hello.go 文件,贴入代码:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
执行代码:
$ go run .
Hello, World!
好了,golang之路已开启。
调用三方包
引入 rsc.io/quote
三方包:
package main
import "fmt"
import "rsc.io/quote"
func main() {
fmt.Println(quote.Go())
}
添加新的模块依赖和 sum 值,需要联网:
$ go mod tidy
go: finding module for package rsc.io/quote
go: found rsc.io/quote in rsc.io/quote v1.5.2
跑一跑:
$ go run .
Don't communicate by sharing memory, share memory by communicating.
再多整点代码
接下来我们看看怎么写一个其他人可以使用的模块,首先创建一个新项目 greetings
:
cd && mkdir greetings && cd greetings
初始化:
$ go mod init example.com/greetings
go: creating new go.mod: module example.com/greetings
创建文件 greetings.go,加入代码: