dvsakgec
dvsakgec

Reputation: 3774

What is the use of pkg directory in Go?

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

Upvotes: 33

Views: 36948

Answers (3)

Jess
Jess

Reputation: 3725

~/go/pkg

From How to Write Go Code, we know ~/go/pkg can store third party library. For example:

  1. Create two file main.go and go.mod:
//main.go
package main

import (
    "fmt"
    "github.com/google/go-cmp/cmp"
)

func main() {
    fmt.Println(cmp.Diff("Hello World", "Hello Go"))
}
//go.mod
module example.com/user/hello

go 1.13
  1. Install a third party library
$ ls ~/go/pkg/mod/github.com/google/
...

$ go install example.com/user/hello
go: finding github.com/google/go-cmp v0.5.2
go: downloading github.com/google/go-cmp v0.5.2
go: extracting github.com/google/go-cmp v0.5.2

$ ls ~/go/pkg/mod/github.com/google/
... [email protected]

$ ls ~/go/pkg/mod/github.com/google/[email protected]

And then, you will see a lot of go files, not compile files.

$ ls ~/go/pkg/mod/github.com/google/[email protected]/cmp/
...  example_test.go   options.go   ...

pkg in user project

This pkg is a directory/package of user project. You can see it as Library and it's OK to use by external applications. For more things, you can check here.

Upvotes: 13

Muhammad Soliman
Muhammad Soliman

Reputation: 23786

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

Upvotes: 7

peterSO
peterSO

Reputation: 166598

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.

Upvotes: 31

Related Questions