Help making basic modules

I have been trying to have a main program that prints a message from a separate module, but all the tutorials that I have found are confusing because they give a hello world example, and then skip ahead to other topics like using the test function or importing someone else’s code…

$go env (linux)
GOPATH="/home/user/go"
GOROOT="/usr/local/go"
GO111MODULE=""

Files…
/home/user/go/hello/hello.go
/home/user/go/hello/main.go


hello.go

package hello

fund Hello() string{
return “Hello”
}


main.go

package main

import (
“fmt”
“hello”
)

func main(){
fmt.Println(hello.Hello())
}

In /home/user/go/hello directory I executed go mod init.
go: cannot determine module path for source directory /home/user/go/hello (outside GOPATH, module path must be specified)

So I tried go mod init hello.
go: creating new go.mod: module hello

File go.mod contains:
module hello

go 1.16

If I write go run main.go:
main.go:5:1: found packages hello (hello.go) and main (main.go) in /home/user/go/hello


and if I try to rectify by making a new folder: /home/user/go/main and put main.go in there, and execute go mod init and remove the go.mod that I made before, I get this error:

package hello is not in GOROOT (/usr/local/go/src/hello)

What am I supposed to do for this main program to call the hello module…?

Your main module needs to be able to go get your hello module. If the module path doesn’t tell go get how to get the module (e.g. if the module isn’t a URL, like in your case), it will look in your GOROOT (e.g. like how packages like “fmt”, “io”, etc. work).

I think the way to get this to work would be to use the replace directive to tell go where your hello module is from your main module’s go.mod.

Thank you for replying, it gave me a few paths to investigate. I was able to finally make it work after 8 hours of pulling my hair but that was not the answer for me.
I don’t expect that anyone in the same boat will ever find this, but just in case…

What I had to do:
create $GOPATH/projectname/main.go
create $GOPATH/projectname/hello/hello.go
(My $GOPATH is /home/username/go, because I’m on linux.)


main.go

package main

import (
“fmt”
“projectname/hello”
)

func main(){
fmt.Println(hello.Hello())
}


hello/hello.go

package hello

func Hello() string{
return “Hello”
}

After this, in projectname folder I had to type
go mod init projectname

And now “go run main.go” finally works and returns “Hello”.

I can finally start coding. And it’s unbelievable that I had to figure some of this out myself. All the beginner tutorials for Go are horrible.