Golang 挖坑之旅——module replace
0. 问题描述
问题1:
问题2:
1. 实验设计
实验环境:
上述两个问题可以通过一个实验来验证,下面给出项目目录:
1 2 3 4 5 6 7 8 9 10 | # 这个项目内包含三个module,其中mod1引用mod2,mod2引用mod3 mod1 go.mod main.go mod2 go.mod mod2.go mod3 go.mod mod3.go |
项目结构相对好理解,为了简便,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | // mod1/go.mod module mod1 go 1.14 require ( nothing.com/mod2 v0.0.0 // 随便起的域名,经过替换repalce,不会下载东西 nothing.com/mod3 v0.0.0 // indirect ) replace nothing.com/mod2 => ../mod2 replace nothing.com/mod3 => ../mod3 // mod1/main.go package main import ( "nothing.com/mod2" ) func main() { mod2.Message() } // mod2/go.mod module mod2 go 1.14 require nothing.com/mod3 v0.0.0 replace nothing.com/mod3 ../notExist // mod2/mod2.go package mod2 import "fmt" import "nothing.com/mod3" func Message() { fmt.Println("Now in mod2") mod3.Message() } // mod3/go.mod module mod3 go 1.14 // mod3/mod3.go import "fmt" func Message() { fmt.Println("Now in mod3") } |
简单说一下实验设计的目的:
上面
2. 实验结果
1 2 3 4 5 | > cd mod1 > go build > .\mod1.exe Now in mod2 Now in mod3 |
可以看到,是可以正常编译并执行的,这至少说明了两个问题:
mod1 中的replace 直接覆盖了全局的replace ,不然的话,mod2 是肯定找不到mod3 的replace 会对间接依赖生效,因为mod1 就是间接依赖mod3
3. 结果分析
exclude andreplace directives only operate on the current (“main”) module.exclude andreplace directives in modules other than the main module are ignored when building the main module. Thereplace andexclude statements, therefore, allow the main module complete control over its own build, without also being subject to complete control by dependencies. (See FAQ below for a discussion of when to use areplace directive).
个人认为,最关键在这句