我有以下文件:
$GOPATH/src/example.com
├── a
│ ├── a.go
│ └── go.mod
├── b
│ ├── b.go
│ └── go.mod
└── c
├── go.mod
└── main.go
内容包括:
a/a.go
:
package a
func NewA() int {
return 1
}
a/go.mod
:
module example.com/a
go 1.17
b/b.go
:
package b
import A "example.com/a"
func NewB() int {
return A.NewA()
}
b/go.mod
:
module example.com/b
go 1.17
replace example.com/a => ../a
require example.com/a v0.0.0-00010101000000-000000000000 // indirect
c/main.go
:
package main
import "fmt"
import B "example.com/b"
func main() {
fmt.Println(B.NewB())
}
c/go.mod
:
module example.com/c
go 1.17
replace example.com/b => ../b
require example.com/b v0.0.0-00010101000000-000000000000 // indirect
当c
目录中的go run main.go
时,我得到:
../b/b.go:3:8: missing go.sum entry for module providing package example.com/a (imported by example.com/b); to add:
go get example.com/b@v0.0.0-00010101000000-000000000000
go get example.com/b@v0.0.0-00010101000000-000000000000
说:
go: downloading example.com/a v0.0.0-00010101000000-000000000000
example.com/b imports
example.com/a: unrecognized import path "example.com/a": reading https://example.com/a?go-get=1: 404 Not Found
当然,这是一个本地包,在互联网上不可用,并且它在所有必要的go.mod
文件中使用replace
。
如何使用本地包?
如果我将example.com
重命名为example
,我得到:missing dot in first path element
。
引用Go模块参考:replace
指令:
replace
指令仅适用于主模块的go.mod
文件,在其他模块中被忽略。有关详细信息,请参阅最小版本选择。
b/go.mod
中的replace
指令在构建主包/模块时无效。您必须将该replace
指令添加到主模块的go.mod
中。
因此,将其添加到c/go.mod
中。在c
文件夹中运行go mod tidy
后,它将显示如下:
module example.com/c
go 1.17
replace example.com/b => ../b
replace example.com/a => ../a
require example.com/b v0.0.0-00010101000000-000000000000
require example.com/a v0.0.0-00010101000000-000000000000 // indirect
如果c/go.mod
中没有这个replace
,您会看到错误消息,因为go工具试图从example.com
(这是一个现有域(获取包,但它不包含go模块。