Chapter 4 - Packages

Exercise 1: Importing Packages

Solution

To download and install a package at https://github.com/jaymcgavren/car, you’d run:

$ go get github.com/jaymcgavren/car

This program will call all the functions contained in that package and its sub-packages:

package main

// Remember, the import path for a package is its path
// within the "src" subdirectory in your workspace.
import (
	"github.com/jaymcgavren/car"
	"github.com/jaymcgavren/car/headlights"
	// All the .go source files in a package directory are
	// combined into a single package. So this one line
	// will give you access to the functions from both the
	// amplifier.go and speakers.go source files.
	"github.com/jaymcgavren/car/stereo"
	"github.com/jaymcgavren/car/wheels"
)

func main() {
	// Precede all function names with the package name.
	car.OpenDoor()
	// The package name is usually the same as the last
	// segment of the import path. So if you import the
	// "car/headlights" package, you'll refer to it as just
	// "headlights".
	headlights.TurnOn()
	stereo.TurnOn()
	stereo.BoostBass()
	wheels.Steer()
	wheels.Accelerate()
}

Output:

Opening door
Shining headlights
Playing music
Bwomp bwamp BWOOOOMP
Turning front wheels
Peeling out!