If we have bin directory already where executables go then what is the need of pkg directory? Please explain.
Packages are the most powerful part of the Go language. The purpose of a package is to design and maintain a large number of programs by grouping related features together into single units so that they can be easy to maintain and understand and independent of the other package programs.
All downloaded modules are cached locally in your $GOPATH/pkg/mod directory by default. If you import a package to your project without downloading it first using go get , the latest tagged version of the module providing that package will be installed automatically and added to your go.
To import a package, we use import syntax followed by the package name. 💡 Unlike other programming languages, a package name can also be a subpath like some-dir/greet and Go will automatically resolve the path to the greet package for us as you will see in the nested package topic ahead.
In Go, a package is a directory of .go files, and packages form the basic building blocks of a Go program. Using packages, you organize your code into reusable units. A module, on the other hand, is a collection of Go packages, with dependencies and versioning built-in.
The pkg
directory contains Go package objects compiled from src
directory Go source code packages, which are then used, at link time, to create the complete Go executable binary in the bin
directory.
We can compile a package once, but link that object into many executables. For example, the fmt
package appears in almost every Go program. It's compiled once but linked many times, a big saving.
You put your source code in src
directory while pkg
is the directory that holds compilation output of your actual source code. If you use multiple libraries/packages you will have different output with extension .a
for each one, A linker
should be responsible for linking and combining all of them together to produce one final executable in bin
directory.
As pkg
and bin
are more specific to the machine or operating system into which you build your actual source code so it is not recommended to share both of them, your repo should have only your actual code.
A side note, if you plan to use docker containers, pkg
dir should be ignored as we may build the source code in windows
for example while you import/mount
your code into linux
container; at this time pkg
will have compiled files that are only valid for windows
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With