Packages

Every Go program is made up of packages. Programs start running in package main. Every program must start with the package declaration. So it is necessary to mark the entry file with the name package main.

package main

import (
	"fmt"
	"math/rand"
)

func main() {
	fmt.Println("My favorite number is", rand.Intn(10))
}

The main package will also contain main function which is the entry function of the program.

Importing Packages

To import packages use import statement like the above:

import (
	"fmt"
	"math/rand"
)

It imports two packages fmt and math/rand. This syntax is called factored import statement. Because it grouped multiple import statement into a single statement. You can seperately import the packages like the following:

// The above import is equivalent to

import "fmt"
import "math/rand"

But it is good style to use the factored import statement.

Exported Vs Unexported names

In Go, a name is exported if it begins with a capital letter. For example, Pizza is an exported name, as is Pi, which is exported from the math package.

pizza and pi do not start with a capital letter, so they are not exported.

When importing a package, you can refer only to its exported names. Any "unexported" names are not accessible from outside the package.

package main

import (
	"fmt"
	"math"
)

func main() {
	fmt.Println(math.pi)
}

The above code will produce the following output:

./prog.go:9:14: cannot refer to unexported name math.pi
./prog.go:9:14: undefined: math.pi

To fix the problem, rename math.pi to math.Pi and try it again.