[英]Go: Multiple Modules
I'm trying to understand Go modules and create a simple hello world program.我正在尝试了解 Go 模块并创建一个简单的 hello world 程序。 Go version:
1.16.2
Go 版本:
1.16.2
/project1
/project1/main.go
/project1/helpers/helpers.go
helpers.go
will contain some utility method like: helpers.go
将包含一些实用方法,例如:
package ???
import "fmt"
func DoSomething() {
fmt.Println("Doing something in helpers.go")
}
main.go
will use methods from helpers.go
like this: main.go
将使用helpers.go
中的方法,如下所示:
package main
import "??"
func main() {
helpers.DoSomething()
}
VSCode is not allowing me to do this and has a red underline on helpers
. VSCode 不允许我这样做,并且在
helpers
上有一个红色下划线。
What am I missing here?我在这里想念什么? How can I achieve this?
我怎样才能做到这一点?
Edit 1: Adding go.mod and package names:编辑 1:添加 go.mod 和 package 名称:
So I ran go mod init helpers
in /helpers
folder and came out with this:所以我在
/helpers
文件夹中运行了go mod init helpers
并得出了以下结果:
/project1/helpers/helpers.go
/project1/helpers/go.mod
go.mod go.mod
module helpers
go 1.16
My main.go
now looks like this:我的
main.go
现在看起来像这样:
package main
import (
"fmt"
"helpers"
)
func main() {
fmt.Println("blah")
helpers.DoHelperMethod()
}
Your project should have only one go.mod
file and it should be in the root of the project.您的项目应该只有一个
go.mod
文件,它应该在项目的根目录中。 You can cd
into the project's directory and do go mod init <module_name>
where <module_name>
in your case can be project1
.您可以
cd
进入项目目录并执行go mod init <module_name>
其中<module_name>
在您的情况下可以是project1
。
For example, once you've initialized the module, your project should look something like the following:例如,一旦你初始化了模块,你的项目应该如下所示:
/project1/helpers/helpers.go
/project1/main.go
/project1/go.mod
go.mod
module project1
go 1.16
main.go
package main
import "project1/helpers"
func main() { helpers.DoHelperMethod() }
helpers/helpers.go
package helpers
func DoHelperMethod() {
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.