Need help to understand the confusion that is Golangs package and module system

704 Views Asked by At

Honestly, Golang's package and module system seems to be the most needlessly complex thing I've ever had to deal with. I don't know if it's just me not understanding, a lack of information on this subject, or just Golang in general.

I've created a Go project that I don't want to publish just yet or upload to GitHub yet. It's not inside the GOPATH that I set up because from what I understand with the introduction of modules you can code your projects outside the GOPATH. The project layout is like this

──── MyProject
     ├─── project
     │    ├─── pkg1
     │    │    └─── foo.go
     │    ├─── pkg2
     │    │    └─── bar.go
     │    └─── go.mod
     └─── test
          └─── test.go

In test.go I'd hope that I could do something like import "project/pkg1" but I can't understand how to get it to work. Even if I move test.go inside the project and I type import "/pkg1" I get a Cannot import absolute path error.

I really don't want to have to code all my go projects inside the %GOPATH%/src all the time, it seems silly to have to do that.

Again this is probably just me not understanding. Any help on this, whether it be a link to a tutorial or website, would be appreciated. Thanks.

1

There are 1 best solutions below

0
On

If you are new with go I recommend using go.mod and a flat project structure. Keep your tests with actual code. Anything suffixed with _test.go will not be included.

go.mod
foo.go
foo_test.go
bar.go
bar_test.go

If this is a library put package name whatever you want.

If this is an executable application set main as root package name.