问题
If we have bin directory already where executables go then what is the need of pkg directory? Please explain.
回答1:
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.
回答2:
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
回答3:
~/go/pkg
From How to Write Go Code, we know ~/go/pkg
can store third party library. For example:
- Create two file
main.go
andgo.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
- 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/
... go-cmp@v0.5.2
$ ls ~/go/pkg/mod/github.com/google/go-cmp@v0.5.2
And then, you will see a lot of go files, not compile files.
$ ls ~/go/pkg/mod/github.com/google/go-cmp@v0.5.2/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.
来源:https://stackoverflow.com/questions/47369621/what-is-the-use-of-pkg-directory-in-go