参考文章 https://mp.weixin.qq.com/s/g4_HWOzL3NNFvyOHseLE6Q。
- 首先创建目录 src/github.com/gopherguides
- mkdir cmd 和 mkdir creatures
- 执行go mod
- cd cmd && go mod init github.com/gopherguides/cmd
- cd go creature && mod init github.com/gopherguides/creature
- 新增 main.go 和 creature.go 文件
- creature.go
package creature
import (
"math/rand"
)
var creatures = []string{"shark", "jellyfish", "squid", "octopus", "dolphin"}
func Random() string {
i := rand.Intn(len(creatures))
return creatures[i]
}
- main.go
package main
import (
"fmt"
"github.com/gopherguides/creature"
)
func main() {
fmt.Println(creature.Random())
fmt.Println(creature.Random())
fmt.Println(creature.Random())
fmt.Println(creature.Random())
}
- 此时import会找不到 github.com/gopherguides/creature 包,需要在go.mod里指定包路径
- 运行命令:go mod edit -replace github.com/gopherguides/creature=…/creature
cmd/go.mod
module github.com/gopherguides/cmd
go 1.20
replace github.com/gopherguides/creature => ../creature
第一行告诉编译器,我们创建的 cmd 包实际上是 github.com/gopherguides/cmd。
第二行告诉编译器,github.com/gopherguides/creature可以在磁盘上的 …/creature 目录下找到。
creature/go.mod
module github.com/gopherguides/creature
go 1.20
这告诉编译器,我们创建的 creature 包实际上是 github.com/gopherguides/creature 包。没有这个,cmd 包就不知道从哪里导入这个包。
- cd cmd && go mod tidy
cmd/go.mod
module github.com/gopherguides/cmd
go 1.20
replace github.com/gopherguides/creature => ../creature
require github.com/gopherguides/creature v0.0.0-00010101000000-000000000000
- cd cmd && go run main.go