Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of pkg directory in Go?

Tags:

If we have bin directory already where executables go then what is the need of pkg directory? Please explain.

like image 813
dvsakgec Avatar asked Nov 18 '17 18:11

dvsakgec


People also ask

What is the purpose of a package in Go?

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.

Where are Go packages stored?

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.

How do I import packages to 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.

What is the difference between package and module in Go?

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.


2 Answers

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.

like image 177
peterSO Avatar answered Sep 28 '22 06:09

peterSO


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

like image 34
Muhammad Soliman Avatar answered Sep 28 '22 06:09

Muhammad Soliman