引用本地的Go模块 [英] Referencing a Go module that is local

查看:42
本文介绍了引用本地的Go模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从本地项目(Go模块)导入包一直没有成功.这是我正在尝试的简介:

I've been unsuccessful in importing a package from a local project (a Go module). Here is a brief of what I'm trying:

我创建了一个Go模块包,如下所示:

I created a Go module package like so:

  $ cd 
  $ mkdir mymodule
  $ cd mymodule
  $ go mod init github.com/Company/mymodule

然后,我在 mymodule 下添加了 hello.go ,并提供了一些小功能

Then I added hello.go under the mymodule with a little function

// mymodule/hello.go

package mymodule

func sayHello() string {
    return "Hello"
}

开始构建成功.

请注意,该模块尚未推送到github存储库.在推送到github之前,我想使用(也许测试)mymodule.因此,我创建了另一个程序包,如下所示:

Note that the module is not pushed to github repository yet. I want to use (and perhaps test) mymodule before I push to github. So I created another package, like so:

  $ cd 
  $ mkdir test
  $ cd test
  $ go mod init github.com/Company/test

然后,在 test 目录下创建一个新文件 test.go ,然后在其中尝试导入 mymodule ,如下所示:

Then, created a new file test.go under the test directory and in there I try to import mymodule, like so:

// test/test.go

import (
    "fmt"
    "github.com/Company/mymodule"
)

func testMyModule() {
    fmt.Println(mymodule.sayHello())
}

但是 test go build 失败,并出现以下错误.有什么作用?

But go build of test fails with the below error. What gives?

cannot load github.com/Company/mymodule: cannot find module providing package github.com/Company/mymodule

推荐答案

在您的 go.mod 中解析依赖项时,Go会尝试通过从远程URL提取第三方模块来解析第三方模块您提供的.

When resolving dependencies in your go.mod, Go will try to resolve the third-party modules by fetching them from the remote URL that you've provided.

远程URL(除非您已将其推送到GitHub)不存在.这是当您收到这样的错误时:

The remote URL, unless you've pushed it to GitHub for example, doesn't exist. This is when you get an error like this:

cannot load github.com/Company/mymodule: cannot find module providing package github.com/Company/mymodule

对于本地模块有一种解决方法,您可以在 go.mod 文件中使用 replace 关键字.

There is a work-around for local modules, you can use the replace keyword in your go.mod file.

replace github.com/Company/mymodule v0.0.0 => ../mymodule

这将使Go知道在哪里可以找到您的本地依赖项.只需确保使用正确的模块相对路径即可.

This will let Go know where to find your local dependency. Just make sure to use the correct relative path to your module.

完成本地测试并将模块推送到存储库后,即可从 go.mod 中删除 replace 行并使用

Once your local tests are complete and you've pushed your module to a repository, then you can remove the replace line from your go.mod and use

go get -u github.com/Company/mymodule`

使模块与当前项目一起正常工作.

to get the module correctly working alongside your current project.

请注意,Go软件包中的函数和变量应以大写字母开头,以便可以从软件包本身外部进行访问.

As a side note, functions and variables in Go packages should start with a capital letter to be accessible from outside the package itself.

祝你好运!

这篇关于引用本地的Go模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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