简体   繁体   English

Go:多个模块

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM