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

Creating Your Own Packages

Creating your own package is like starting your own labeled toolbox drawer that other parts of your project (or other people's projects) can borrow tools from.

Creating a Package Directory

To create a reusable package, make a new subdirectory and give every .go file inside it the same package declaration, matching the directory's purpose -- for example a mathutils folder containing 'package mathutils'.

Example: Creating a Package Directory

markup
package main

import "fmt"

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

Exporting Identifiers

Only capitalized function, type, and variable names in a package are visible to code importing it -- lowercase identifiers remain private implementation details, invisible outside the package.

Example: Exporting Identifiers

markup
package main

import "fmt"

// Simulating what would live in a separate mathutils package file:
// func Add(a, b int) int { return a + b }       -- exported, usable elsewhere
// func subtractInternal(a, b int) int { ... }    -- unexported, package-private

func Add(a, b int) int {
	return a + b
}

func main() {
	fmt.Println(Add(3, 4))
}

Importing Your Own Package

A package you write is imported the same way as a third-party one, using its full path built from the module's name (in go.mod) plus its subdirectory, e.g. github.com/example/myapp/mathutils.

Note: The import path is always relative to the module path declared in go.mod's first line.

Example: Importing Your Own Package

markup
package main

import "fmt"

func main() {
	fmt.Println("import \"github.com/example/myapp/mathutils\"")
	fmt.Println("then call: mathutils.Add(3, 4)")
}
Common Mistakes
  1. Forgetting to capitalize an identifier that's meant to be usable from other packages, leaving it unintentionally private.
  2. Creating a package with an overly generic name like util or common that becomes a dumping ground for unrelated code.
  3. Placing package code in the wrong directory relative to the module root, breaking its expected import path.
Chapter Summary
  • A custom package is just a directory of .go files sharing one package name, other than main.
  • The package is imported using its path relative to the module root, as declared in go.mod.
  • Exported identifiers (capitalized) become the package's public API for other code to use.
  • Well-designed packages have a small, focused responsibility rather than being a catch-all.
🔒

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.