I can't use packages

I’m having problems to use packages. I a following literally the steps I find online, but I have an error message.

I have this package in GOPATH:
go/src/greet/day.go

package greet

var morning = "Good morning"
var Morning = "hey" + morning

I want to import it in my code:
go/src/app/entry.go

package main

import ("fmt"
        "greet")

func main(){
    fmt.Println(greet.Morning)
}

When I run entry.go, I receive this message: entry.go:4:3: package greet is not in GOROOT (/usr/local/go/src/greet)

Does anybody how to fix it?

Thank you.

Modern go does not rely on GOPATH anymore.

Please use proper modules with an appropriate module path.

1 Like

Thanks a lot for help!

In order to use a package, Go has to know where the package is. There are two ways to do this in your example. But first, move the directories outside of $GOPATH.

If you want “greet” to be a library that you can use and maintain as a separate project, independently of “app”, then you have two modules. If “greet” and “app” are in the same parent directory, then:

cd greet
go mod init greet
go mod tidy
cd ../app
go mod init app

edit app/go.mod and add this line:

replace greet => ../greet

then:

go mod tidy
go build entry.go

“go mod init” creates a go.mod file, that you can also create or edit by hand.
“go mod tidy” creates a go.sum file.

It doesn’t matter what you name the app module, if you don’t import it anywhere else. You could have named it “main” (go mod init main).

The situation is simpler if you put greet/ and app/ in the same module. Move app/ inside greet/, so that you have the file structure:

greet/day.go
greet/app/entry.go

First, remove any go.mod, go.sum files from the previous step.
Then:

cd greet
go mod init greet
go mod tidy
cd ./app
go build entry.go

In both cases you have two packages, but in the first case you have two modules, while in the second case you have one module.