一、说明
这篇指导,介绍Go中基础的多模块工作空间。使用多模块工作空间。你能告诉Go命令,你将同时在多模块写代码,并且很容易在这些模块构建和运行代码。
在这篇指导中,你将用一个共享的多模块工作空间创建两个模块。跨越这些模块进行更改,并且在构建中看到这些结果的改变。
二、准备
- 安装Go 1.18 或更高版本;
- 一个编辑代码的工具;
- 一个命令行终端;
三、为你的代码查u你更加爱你一个模块
$ cd
$
$ mkdir workspace
$ cd workspace/
$
$ mkdir hello
$ cd hello/
$ go mod init example.com/hello
go: creating new go.mod: module example.com/hello
$
$ go get golang.org/x/example
go: downloading golang.org/x/example v0.0.0-20220412213650-2e68773dfca0
go: added golang.org/x/example v0.0.0-20220412213650-2e68773dfca0
$
package main
import (
"fmt"
"golang.org/x/example/stringutil"
)
func main() {
fmt.Println(stringutil.Reverse("Hello"))
}
$ go run example.com/hello
olleH
$
四、创建工作空间
go.work
4.1 初始化工作空间
workspace
$ go work init ./hello
$
go work init./hellogo.work
go.work
$ ll
total 8
drwxr-xr-x 4 lifei staff 128 8 22 22:30 ./
drwxr-xr-x 6 lifei staff 192 8 22 22:18 ../
-rw-r--r-- 1 lifei staff 21 8 22 22:30 go.work
drwxr-xr-x 5 lifei staff 160 8 22 22:26 hello/
$ cat go.work
go 1.18
use ./hello
$
go.workgo.mod
go.mod
usehello
workspace
workspace
$ go run example.com/hello
olleH
$
go run
golang.org/x/examplestringutilReverse
golang.org/x/example
golang.org/x/examplehello
$ git clone https://go.googlesource.com/example
Cloning into 'example'...
remote: Total 204 (delta 93), reused 204 (delta 93)
Receiving objects: 100% (204/204), 103.24 KiB | 1006.00 KiB/s, done.
Resolving deltas: 100% (93/93), done.
$
$ go work use ./example
$
$ cat go.work
go 1.18
use (
./example
./hello
)
$
package stringutil
import "unicode"
// 将参数中的所有字符转成大写
func ToUpper(s string) string {
r := []rune(s)
for i := range r {
r[i] = unicode.ToUpper(r[i])
}
return string(r)
}
package main
import (
"fmt"
"golang.org/x/example/stringutil"
)
func main() {
// fmt.Println(stringutil.Reverse("Hello"))
fmt.Println(stringutil.ToUpper("Hello"))
}
$ go run example.com/hello
HELLO
$
更进一步:
v0.1.0
发布完成后,我们可以在 hello/go.mod 中增加对 golang.org/x/example 模块的要求:
$ cd hello/
$ go get golang.org/x/example@v0.1.0
这样, go 命令可以正确解析工作区之外的模块。
六、更多关于工作空间
go work use [-r] [dir]-r go work edit go.workgo mod editgo work sync