I'm using go 1.6 (I need to update). Let's say I have 2 files in a package, and I'm using the fmt
package in both of them. You have to explicitly import fmt
in both of those files, or the compiler throws and error, so does that mean it stores the fmt
binary in my executable twice?
1 Answers
No, that would be a really poor design (read exception at the end). By the way, it is very easy to check this, create a package named a
, consisting of 2 files: aa.go
and ab.go
. Have both import fmt
. Produce the executable (e.g. go build
, must called on the main
package) and check its size. Now move all code from ab.go
that uses the fmt
package to aa.go
, and remove the fmt
import from ab.go
. Produce the executable again. They will have the same size.
Packages are identified by their full path. No matter how many files (of the same package) or how many (different) packages refer to a package, the package will only be included once in the final executable binary.
Also note that not everything will be included from used packages in the executable binary. Certain things that are not used / referred to may be excluded. For details see Splitting client/server code; and How to remove unused code at compile time?
There is one exception though, which is the plugins introduced in Go 1.8. Packages referred to by plugins will be included in the compiled plugin –they have to be–, because the plugin has no guarantee what packages will be available in the executable binary that will load it. So if the fmt
package is referred to by package main
, and also by a plugin, the code of the fmt
package will be included in both (in the executable binary and in the compiled plugin). It should be noted that even though the fmt
package's code will be present twice (once in the executable and once in the plugin), there will still be only one "instance" of the package in the runtime (in memory) (e.g. its global variables will have one instance, and it will only be initialized once).
An "edge" case is vendored packages. If a package is vendored in a vendor
folder, and a package refers to this vendored package, that is considered distinct from the original (that is vendored), and if the original is also referred to by another package, both will be included in the executable binary (but they are not considered the same, the full path of the vendored is different from the full path of the original).

- 389,944
- 63
- 907
- 827