Go Module机制下本地包调用问题
使用Go Module 调用本地包
困扰新手许久的问题
调用非同一项目下的本地包
结构如下:
└── test1
├── test2
│ ├── go.mod
│ └── main.go
└── test3
├── go.mod
└── utils.go
调用本地包的测试
vim test1/test2/main.go
package main
import "test3"
func main() {
test3.Test3Print()
}
vim test1/test3/utils.go
package test3
import "fmt"
func Test3Print() {
fmt.Println("test3.Print")
}
对test2 和 test3 分别初始化
cd test1/test3
go mod init
cd ../test2
go mod init
不同项目情况下导入包需要在go.mod文件进行replace
使用go module导入本地包
如test2/go.mod
module exercise/test1/test2
go 1.20
replace test3 => ../test3
$ go get test3
go: added test3 v0.0.0-00010101000000-000000000000
但在运行test2/main.go 依旧报错
$ go run main.go
main.go:3:8: package test3 is not in GOROOT (/home/xxx/go/go1.20.1/src/test3)
————问题已解决————
目前已知是workspace的问题
在$GOPATH
下进行
go work init
目前看到的配置gopath的资料都是单进行了初始化,但不知道什么原因在我的系统中仅做初始化workspace不会去搜索module
因此,在$GOPATH
中需要额外进行
go work use .
即可正常使用go module