I have been using Go and have read at some places that Go compiler needs to only include the packages that you are importing directly from main
.
As a result, the time it takes to resolve dependency is linear as compared to C++ where its exponential. How does that work?
If main
imports package alpha
which in turn imports package beta
then wouldn't Go compiler need to compile the whole tree?
The Go compiler first compiles a single package into a single object file. At this stage, it only needs to resolve all the import
s it finds in the package it compiles. For the object file of your package, there are only calls to the same package or direct imports, so there's no issue here. A separate linking stage links all object files together. There's a decent explanation of this in the doc of the compile package:
Compile, typically invoked as “go tool compile,” compiles a single Go package comprising the files named on the command line. It then writes a single object file named for the basename of the first source file with a .o suffix. The object file can then be combined with other objects into a package archive or passed directly to the linker (“go tool link”). If invoked with -pack, the compiler writes an archive directly, bypassing the intermediate object file.
The generated files contain type information about the symbols exported by the package and about types used by symbols imported by the package from other packages. It is therefore not necessary when compiling client C of package P to read the files of P's dependencies, only the compiled output of P.