'Creating a project with Go modules

I'm trying to understand Go modules and create a simple hello world program. Go version: 1.16.2

/project1
/project1/main.go
/project1/helpers/helpers.go

helpers.go will contain some utility method like:

package ???

import "fmt"

func DoSomething() {
  fmt.Println("Doing something in helpers.go")
}

main.go will use methods from helpers.go like this:

package main

import "??"

func main() {
  helpers.DoSomething()
}

VSCode is not allowing me to do this and has a red underline on helpers.

What am I missing here? How can I achieve this?


Edit 1: Adding go.mod and package names:

So I ran go mod init helpers in /helpers folder and came out with this:

/project1/helpers/helpers.go
/project1/helpers/go.mod

go.mod

module helpers

go 1.16

My main.go now looks like this:

package main

import (
    "fmt"
    "helpers"
)

func main() {
    fmt.Println("blah")
    helpers.DoHelperMethod()
}


Solution 1:[1]

Your project should have only one go.mod file and it should be in the root of the project. You can cd into the project's directory and do go mod init <module_name> where <module_name> in your case can be 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() {
    // ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mkopriva