在 go 模块中访问本地包(go 1.11) [英] Accessing local packages within a go module (go 1.11)
问题描述
我正在试用 Go 的新模块系统,但在访问本地包时遇到问题.以下项目位于我的 gopath 之外的桌面文件夹中.
我的项目结构如下:
<预><代码>/-/平台-platform.go- main.go- go.mod<小时>
//platform.go包裹平台导入fmt"功能打印(){fmt.Println("嗨")}
<小时>
//main.go包主导入平台"功能主(){平台.打印()}
go build main.go
告诉我
找不到路径平台的模块
我强烈建议您使用 go 工具链,它开箱即用地处理这些问题.带有 vscode-go 插件的 Visual Studio Code 真的很有用.
这里的问题是 Go 需要相对于 import 语句中的 $GOPATH/src
或 module
的相对路径.根据您在 GOPATH
中的位置,导入路径也应包含该内容.在这种情况下,import 语句必须在 go.mod
GOPATH
假设您的项目位于此处:
$GOPATH/src/github.com/myuser/myproject
您的导入路径应该是:
import "github.com/myuser/myproject/platform"
VGO
假设你的 go.mod 文件是:
module example.com/myuser/myproject
您的导入路径应该是:
import "example.com/myuser/myproject/platform"
I'm trying out Go's new modules system and am having trouble accessing local packages. The following project is in a folder on my desktop outside my gopath.
My project structure looks like:
/
- /platform
- platform.go
- main.go
- go.mod
// platform.go
package platform
import "fmt"
func Print() {
fmt.Println("Hi")
}
// main.go
package main
import "platform"
func main() {
platform.Print()
}
go build main.go
tells me
cannot find module for path platform
I would strongly suggest you to use go toolchain which takes care of these issues out of the box. Visual Studio Code with vscode-go plugin is really useful.
Problem here is that Go requires relative paths with respect to your $GOPATH/src
or module
in import statement. Depending on where you are in your GOPATH
, import path should include that as well. In this case, import statement must include go module path in go.mod
GOPATH
Assume your project resides here:
$GOPATH/src/github.com/myuser/myproject
Your import path should be:
import "github.com/myuser/myproject/platform"
VGO
Assume your go.mod file is:
module example.com/myuser/myproject
Your import path should be:
import "example.com/myuser/myproject/platform"
这篇关于在 go 模块中访问本地包(go 1.11)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!