Go was designed to be a language that encourages good software engineering practices. An important part of high quality software is code reuse – embodied in the principle “Don't Repeat Yourself.”

As we saw in chapter 7 functions are the first layer we turn to allow code reuse. Go also provides another mechanism for code reuse: packages. Nearly every program we've seen so far included this line:

import "fmt"

fmt is the name of a package that includes a variety of functions related to formatting and output to the screen. Bundling code in this way serves 3 purposes:

Creating Packages

Packages only really make sense in the context of a separate program which uses them. Without this separate program we have no way of using the package we create. Let's create an application that will use a package we will write. Create a folder in ~/src/golang-book called chapter11. Inside that folder create a file called main.go which contains this:

package main

import "fmt"
import "golang-book/chapter11/math"

func main() {
  xs := []float64{1,2,3,4}
  avg := math.Average(xs)

Now create another folder inside of the chapter11 folder called math. Inside of this folder create a file called math.go that contains this:

package math

func Average(xs []float64) float64 {
  total := float64(0)
  for _, x := range xs {
    total += x
  return total / float64(len(xs))

Using a terminal in the math folder you just created run go install. This will compile the math.go program and create a linkable object file: ~/pkg/os_arch/golang-book/chapter11/math.a. (where os is something like windows and arch is something like amd64)

Now go back to the chapter11 folder and run go run main.go. You should see 2.5. Some things to note:


Go has the ability to automatically generate documentation for packages we write in a similar way to the standard package documentation. In a terminal run this command:

godoc golang-book/chapter11/math Average

You should see information displayed for the function we just wrote. We can improve this documentation by adding a comment before the function:

// Finds the average of a series of numbers
func Average(xs []float64) float64 {

If you run go install in the math folder, then re-run the godoc command you should see our comment below the function definition. This documentation is also available in web form by running this command:

godoc -http=":6060"

and entering this URL into your browser:


You should be able to browse through all of the packages installed on your system.


← Previous Index Next →