我正在尝试让 Go 模块在不涉及远程存储库的情况下工作。
src
是一个本地目录,里面包含了我所有的项目,还有用 Go 以外的其他语言编写的项目。为简单起见,我只显示了与我的问题相关的两个目录:
src
├── client
│ ├── go.mod
│ └── main.go
└── lib
├── go.mod
└── lib.go
go.mod
文件是通过在 src/client
和 go mod init 中运行命令
。go mod init client
创建的src/lib
中的 lib
src/client/main.go:
package main
import "lib"
func main() {
lib.Hello()
}
src/lib/lib.go:
package lib
import "fmt"
func Hello() {
fmt.Println("Hello World")
}
我想做的是在我的 main.go 中使用库 lib.go,但无论我在导入路径中放入什么,都会显示此错误:
main.go:3:8: package lib is not in GOROOT (/usr/lib/go/src/lib)
Go版本是go1.14.3
如何从本地文件夹正确导入 Go 代码?
最佳答案
您可以使用replace
指令。
项目结构:
root
├── client
│ ├── go.mod
│ └── main.go
└── lib
├── go.mod
└── lib.go
root/lib
模块的 go.mod
:
module github.com/owner/root/lib
go 1.13
root/client
模块的 go.mod
:
module github.com/owner/root/client
go 1.13
require github.com/owner/root/lib v0.0.0
replace github.com/owner/root/lib => ../lib
This is terrible, do you really have to do this for every import if there is no VCS?
没有。 replace指令替换模块特定版本的内容,并包含属于替代模块的包。
root
├── client
│ ├── go.mod
│ └── main.go
└── lib
├── utils
│ └── util.go
├── libs
│ └── lib.go
└── go.mod
package main
import (
"github.com/owner/root/lib/utils"
"github.com/owner/root/lib/libs"
)
func main() {
//...
}
关于没有远程存储库的 Go 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62164408/