Organizing Code Across Files
Start with Organizing Code Across Files
A Go package may contain several source files so that related code can be separated without forcing new packages.
What you’ll learn
- Explain the main purpose of organizing code across files.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Files in one directory using the same package are compiled together. A function declared in helper.go can be called by code in main.go without importing the same package. For complete package builds use go run . or go build . from the appropriate module directory.
go run main.go compiles only the explicitly named file, so it can report an undefined helper when the helper lives in another file. Choose directory-level commands when learning multi-file layout.
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 files, one package
calculator/
go.mod
main.go
helper.gomain.go:
package main
import "fmt"
func main() { fmt.Println(square(6)) }helper.go:
package main
func square(n int) int { return n * n }From this module folder, run go run ..
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"
func square(number int) int { return number * number }
func main() { fmt.Println("Square:", square(6)) }
Output
Square: 36Trace what the program does
This self-contained example defines the helper in the same file. The module example below places the same function in helper.go while main.go continues to call square.
Avoid common mistakes
- Do not accidentally place
package helpersin the same ordinary source directory aspackage main. - When a command names only main.go, it excludes helper.go unless you explicitly name it.
Try it yourself
Move square into helper.go, leave main in main.go, and execute go run ..
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 Organizing Code Across Files 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.