Creating Custom Packages
Start with Creating Custom Packages
Custom packages let you reuse functions in multiple files or programs while keeping a clear dependency direction.
What you’ll learn
- Explain the main purpose of creating custom packages.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Create a directory such as greeting/ containing package greeting. Declare func Message(name string) string with an initial capital so callers in another package can use it. In a module called example.com/hello, the import path becomes example.com/hello/greeting.
The executable imports this package; the reusable package does not need its own main(). When developing locally, Go resolves packages within the current module without publishing the module online.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
Two-package project
hello/
go.mod
main.go
greeting/
greeting.goRun go mod init example.com/hello inside hello/. Put the following in greeting/greeting.go:
package greeting
func Message(name string) string {
return "Hello, " + name
}Use the package from main.go:
package main
import (
"fmt"
"example.com/hello/greeting"
)
func main() {
fmt.Println(greeting.Message("Go"))
}Execute go run . from the module root.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
// In a separate package, an exported Message function is callable here.
func message(name string) string { return "Hello, " + name }
func main() { fmt.Println(message("Go")) }
Output
Hello, GoTrace what the program does
This one-file equivalent demonstrates a helper returning a string, so it runs in an online compiler. The multi-file project below moves the helper into its own package.
Avoid common mistakes
- The filename need not match the package name; the directory package declaration matters.
- Do not import a package by an arbitrary filesystem relative path; use its module import path.
Try it yourself
Create the two-file directory example and change the exported greeting function to include an exclamation mark.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Creating Custom Packages in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.