← Back to Go Course | Chapter 10: Packages & Modules | Lesson 1 of 6

Package Basics

A package is a labeled folder of Go code that groups related helpers together, like a labeled drawer in a toolbox holding only screwdrivers.

Declaring a Package

Every Go source file begins with 'package name', declaring which package it belongs to. Files sharing a directory and package name form one cohesive unit that can share unexported identifiers between them.

Example: Declaring a Package

markup
package main

import "fmt"

func main() {
	fmt.Println("this file belongs to package main")
}

One Package Per Directory

All .go files directly within a single directory must declare the same package name (aside from a special _test package suffix for external test files) -- Go organizes code by directory, not by individual file.

Example: One Package Per Directory

markup
package main

import "fmt"

func main() {
	fmt.Println("mathutils/add.go: package mathutils")
	fmt.Println("mathutils/subtract.go: package mathutils")
}

package main Is Special

Only package main, combined with a func main(), can be compiled into a standalone executable with 'go build'. Every other package name produces a library meant to be imported, never run directly.

Example: package main Is Special

markup
package main

import "fmt"

func main() {
	fmt.Println("Only package main can be built into a runnable binary")
}
Common Mistakes
  1. Putting multiple different package names in files within the same directory -- every .go file in one directory must declare the same package name.
  2. Assuming the package name must match the directory name exactly -- it's conventional, but Go only requires consistency within the directory itself.
  3. Forgetting that package main is special: only it can produce a runnable binary, everything else builds as a library.
Chapter Summary
  • Every Go file starts with a package declaration grouping it with other files in the same directory.
  • All .go files directly inside one directory must share the same package name.
  • package main is reserved for producing a runnable executable; other names produce importable libraries.
  • Packages are Go's unit of code organization and namespacing.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.