appendix AModules and packages

 

We’ll write, compile, and run an executable program that prints the title of this book to the console. This tiny program introduces packages and modules. We’ll discuss packages and implement the program, initialize a new Go module, and run our program. To avoid surprises, you should use the same module you'll initialize in section A.3 throughout the book’s examples while following along.

A.1 Packages

A package is a set of Go source code files in the same directory. Every Go file in a package directory must declare the same package name.

There are two kinds of packages:

  • Packages named main are for building executable programs and cannot be imported from other packages for reuse.
  • Packages named anything but main can be imported from other packages.

Go compiles all files within a package as a single unit, compiling separate packages concurrently to speed the compilation process and finally linking compiled packages into a final binary. Packages form firm boundaries, encapsulating internals and describing how other packages can interact with them.

A.1.1 Example

As shown in figure A.1, our tiny example program has two packages:

  • Package main is the entry point to our executable program.
  • Package book is an importable package. Its Title function returns this book’s title.

A.2 Package main

A.3 Modules

A.4 Building and running

A.5 Exercises