Creating Your Own Packages
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
package main
import "fmt"
func main() {
fmt.Println("myapp/mathutils/add.go declares: package mathutils")
}
Login to try C/C++/Java/PHP code in the editor
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
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))
}
Login to try C/C++/Java/PHP code in the editor
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
package main
import "fmt"
func main() {
fmt.Println("import \"github.com/example/myapp/mathutils\"")
fmt.Println("then call: mathutils.Add(3, 4)")
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting to capitalize an identifier that's meant to be usable from other packages, leaving it unintentionally private.
- Creating a package with an overly generic name like util or common that becomes a dumping ground for unrelated code.
- Placing package code in the wrong directory relative to the module root, breaking its expected import path.
- 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: