本文共 1701 字,大约阅读时间需要 5 分钟。
一个 Go 模块是一个 Go 包的集合,用于发布和分发。通常情况下,一个 Go 仓库只包含一个模块,这个模块必须包含一个 go.mod
文件。
模块路径不仅用于作为包的导入前缀,还帮助 go command
查找和下载模块。例如,导入 golang.org/x/tools
时,go command
会从 https://golang.org/x/tools
下载该模块。
要创建一个新的模块,可以按照以下步骤操作:
创建一个目录:
mkdir hellocd hello
初始化模块:
go mod init example.com/user/hello
这将创建一个 go.mod
文件,内容如下:
module example.com/user/hellogo 1.16
编写 Go 源文件:
package mainimport "fmt"func main() { fmt.Println("Hello, world.")}
构建并安装模块:
go install example.com/user/hello
这将编译模块并将二进制文件安装到 GOPATH
或 GOBIN
目录中。
Go 提供了 go mod
命令来管理模块依赖。使用 go mod tidy
会下载所有引用但尚未下载的依赖,同时移除不必要的依赖。
在 go.mod
文件中可以指定依赖的版本,确保依赖一致性。例如:
require ( "fmt v1.0.0" "example.com/user/hello/morestrings v1.2.3")
Go 提供了 testing
包来编写单元测试。测试文件应以 _test.go
结尾,测试函数应命名为 Test***
并带有 func(t *testing.T)
的签名。
编写测试文件:
package morestringsimport "testing"func TestReverseRunes(t *testing.T) { cases := []struct { in, want string }{ {"Hello, world", "dlrow ,olleH"}, {"Hello, 世界", "界世 ,olleH"}, {"", ""}, } for _, c := range cases { got := ReverseRunes(c.in) if got != c.want { t.Errorf("ReverseRunes(%q) == %q, want %q", c.in, got, c.want) } }}
运行测试:
go test
要引用远程模块,可以直接在 import
语句中使用 URL。例如,引用 github.com/google/go-cmp/cmp
。
package mainimport ( "fmt" "example.com/user/hello/morestrings" "github.com/google/go-cmp/cmp")func main() { fmt.Println(morestrings.ReverseRunes("!oG ,olleH")) fmt.Println(cmp.Diff("Hello World", "Hello Go"))}
运行:
go install example.com/user/hellogo mod tidy
go mod info example.com/user/hello
go clean -modcache
通过以上指南,你可以轻松创建、管理和使用 Go 模块。
转载地址:http://knyiz.baihongyu.com/