Reputation: 41
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()
}
Upvotes: 1
Views: 3573
Reputation: 1
In case if you want to create new module follow below steps:
mkdir newPackage
cd newPackage
go mod init example.com/mypackage
Upvotes: 0
Reputation: 38223
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() {
// ...
}
Upvotes: 6