Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
引用本地的Go模块_Go_Go Modules - Fatal编程技术网

引用本地的Go模块

引用本地的Go模块,go,go-modules,Go,Go Modules,我从本地项目(Go模块)导入包失败。以下是我正在尝试的简要说明: 我创建了一个Go模块包,如下所示: $ cd $ mkdir mymodule $ cd mymodule $ go mod init github.com/Company/mymodule 然后我在mymodule下添加了hello.go,并提供了一些功能 // mymodule/hello.go package mymodule func sayHello() string { return "

我从本地项目(Go模块)导入包失败。以下是我正在尝试的简要说明:

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

  $ cd 
  $ mkdir mymodule
  $ cd mymodule
  $ go mod init github.com/Company/mymodule
然后我在
mymodule
下添加了
hello.go
,并提供了一些功能

// mymodule/hello.go

package mymodule

func sayHello() string {
    return "Hello"
}
go-build
成功

请注意,模块尚未推送到github存储库中。我想在推到github之前使用(或者测试)mymodule。所以我创建了另一个包,如下所示:

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

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

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

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

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

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

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

但是
test
go build
失败,出现以下错误。有什么好处

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

将cd放入github.com/Company/test中


尝试编辑go mod--replace=github.com/Company/mymodule=../mymodule

测试模块中的go.mod可以是:

module github.com/Company/test
require github.com/Company/mymodule v0.0.0
replace github.com/Company/mymodule v0.0.0 => ../mymodule
go 1.12

另外,sayHello函数名必须大写。然后,它将成为公共模块并可导出到其他模块。

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

远程URL不存在,除非您将其推送到GitHub(例如)。当您遇到如下错误时:

cannot load github.com/Company/mymodule: cannot find module providing package github.com/Company/mymodule
对于本地模块有一个变通方法,您可以在
go.mod
文件中使用
replace
关键字

replace github.com/Company/mymodule v0.0.0 => ../mymodule
这将让你知道在哪里可以找到你的本地依赖关系。只需确保使用正确的模块相对路径即可

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

go get -u github.com/Company/mymodule`
使模块与当前项目一起正确工作

作为旁注,Go包中的函数和变量应该以大写字母开头,以便从包本身外部访问


祝你好运

切勿将包或文件称为“测试”。出口你的东西。即使没有模块错误,您的代码也无法工作。是否可以将replace指令放在单独的文件模块文件中?必须修改一个潜在版本连接的文件来进行一些依赖性测试,这似乎既奇怪又危险。。