How do packages with multiple files work in golang?

pymd picture pymd · Jun 5, 2013 · Viewed 12.2k times · Source

This repo has 3 go files all begin with "package lumber". To use this package, I'm supposed to put this in my GOROOT and simply

import lumber

in my program. How do variables and types in this package connect with each other across multiple files? How does the go compiler know which file to begin reading first?

In case I want to read the package, where should I begin reading to understand the package? What exactly is the flow of things here?

Answer

jimt picture jimt · Jun 5, 2013

To elaborate on jnml's answer:

When you use import "foo/bar" in your code, you are not referring to the source files (which will be located in $GOPATH/src/foo/bar/).

Instead, you are referring to a compiled package file at $GOPATH/pkg/$GOOS_$GOARCH/foo/bar.a. When you build your own code, and the compiler finds that the foo/bar package has not yet been compiled (or is out of date), it will do this for you automatically.

It does this by collating* all the relevant source files in the $GOPATH/src/foo/bar directory and building them into a single bar.a file, which it installs in the pkg directory. Compilation then resumes with your own program.

This process is repeated for all imported packages, and packages imported by those as well, all the way down the dependency chain.

*) How the files are collated, depends on how the file itself is named and what kind of build tags are present inside it.

For a deeper understanding of how this works, refer to the build docs.