When to use modules vs packages?

Hey Guys, I’m a new Go Ninja, working towards becoming a Go Jedi!!

I was reading a about modules and packages and I think that I have a good grasp of what they are but I’m still just beginning my Go journey so I wanted to go more in depth in when I should use Modules or Packages so I check out an API that I like a lot here: https://github.com/zmb3/spotify. As we can see, there is a module spotify here and everything is in the package spotify (it’s a simple API so fine) as well so I thought that it might be the way to go, make a module at the root of your repo and then have multiple package under that module if necessary.

But then, I went and double checked to make sure it is the right way to go and examined the Go code itself here: https://github.com/golang/go/tree/master/src/net. I took the net package as an example. I thought that net would be a module and that all the sub folders would be packages like “http”, etc. but it turns out that net itself is a package so now I’m kind of confused as what is the right way to go.

I saw the go blog post about modules that it talks about modules being the new way to go, but I’m still not clear about when I should make my code a module or just a package.

Can anyone clarify that a little bit please?

Thank you so much!

A modules is a collection of packages, and the module is the root of the repository defining it.

You should write a single module, which contains all your packages.

It is good that you looked at the Go standard library, which is a great source for idomatic code.
But it predates modules and works differently.

Worth reading https://golang.org/doc/code.html
which will point you in the right direction.

1 Like