🎓 A1Learner
🔍
0 of 34 lessons completed

Go Packages in Depth

A package is a group of source files that share one package name. Some of its code runs before main, and some of its values are shared by all of its functions.

Init runs before main

The init function sets the package-level message. Main prints after init, so it sees the set value.

package main

import "fmt"

var message string

func init() {
	message = "Ready"
	fmt.Println("Init runs first")
}

func main() {
	fmt.Println(message)
}

Two init functions run in file order

One package can hold more than one init function. They run in the order the file lists them.

package main

import "fmt"

func init() {
	fmt.Println("First init")
}

func init() {
	fmt.Println("Second init")
}

func main() {
	fmt.Println("Main runs last")
}

Two functions share one package-level variable

The counter sits outside any function. Both small functions change the same counter.

package main

import "fmt"

var count int

func addOne() {
	count = count + 1
}

func addFive() {
	count = count + 5
}

func main() {
	addOne()
	addFive()
	fmt.Println(count)
}

Exported names start with a capital letter

Println and ToUpper both start with a capital letter, so this package can use them. A name that starts with a small letter stays inside its own package.

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.ToUpper("exported"))
	fmt.Println(strings.HasPrefix("exported", "ex"))
}

Example

package main

import "fmt"

var lessons int

func init() {
	lessons = 3
	fmt.Println("Lessons loaded:", lessons)
}

func main() {
	fmt.Println("Starting with", lessons, "lessons")
	fmt.Println("First lesson starts")
}

Key points

  • One package gathers the source files that share its name.
  • Use func init to write setup code that runs before main.
  • A package-level variable is declared outside any function.
  • Every function in the package can read and change a package-level variable.
  • The files of one package sit in one folder.
  • A function in one file of a package can call a function in another file of the same package with no import line.
  • An exported name starts with a capital letter and can be used outside its package.

In this example, init sets the package-level lessons count to 3. Init then prints the loaded count. Main runs next and prints the same count. The last line shows the work of main after the setup.

Note

No code calls init directly. The run starts it before main.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Go Playground

Exercise

When does an init function run?