没有远程存储库的模块?
Go modules without remote repository?
我正在尝试让 Go 模块在不涉及远程存储库的情况下工作。
src
是一个本地目录,里面包含了我所有的项目,还有用 Go 以外的其他语言编写的项目。为简单起见,我只显示了与我的问题相关的两个目录:
src
├── client
│ ├── go.mod
│ └── main.go
└── lib
├── go.mod
└── lib.go
go.mod
文件由 运行 src/client
中的 go mod init client
和 src/lib
中的 go mod init 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
go.mod
属于 root/lib
模块:
module github.com/owner/root/lib
go 1.13
go.mod
root/client
模块:
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 模块在不涉及远程存储库的情况下工作。
src
是一个本地目录,里面包含了我所有的项目,还有用 Go 以外的其他语言编写的项目。为简单起见,我只显示了与我的问题相关的两个目录:
src
├── client
│ ├── go.mod
│ └── main.go
└── lib
├── go.mod
└── lib.go
go.mod
文件由 运行 src/client
中的 go mod init client
和 src/lib
中的 go mod init 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
go.mod
属于 root/lib
模块:
module github.com/owner/root/lib
go 1.13
go.mod
root/client
模块:
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() {
//...
}