在 go 模块中访问本地包(go 1.11) [英] Accessing local packages within a go module (go 1.11)

查看:36
本文介绍了在 go 模块中访问本地包(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/srcmodule 的相对路径.根据您在 GOPATH 中的位置,导入路径也应包含该内容.在这种情况下,import 语句必须在 go.mod

中包含 go 模块路径

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆