Multiple files
- Go course
- Beginner
- Lesson 10/90
- 4 min
Learn that a package can span multiple .go files.
Multiple files
A package can consist of multiple .go files. All files carrying the same package name belong to the same package. This is the basic way to split large packages.
For instance, string_utils.go and number_utils.go both declaring package utils are in the same utils package. A definition in one file is visible in the other.
Compilation happens at the package level with go build; not at the file level. All package files compile together.
Package visibility
In Go, visibility is determined by case. Names starting with an uppercase letter are exported and reachable from other packages. Lowercase names stay package-private.
For example, Println is exported, while print stays inside the fmt package. This mechanism replaces public/private in Java.
Within the same package, lowercase names are visible across files because the package is a single scope.
Practice Exported names
Try visibility inside a package: write Topla(a, b int) int, starting with an upper-case letter (exported), and ikiKat(n int) int, starting with a lower-case one (package-private). Print fmt.Println(Topla(2, 3), ikiKat(4)).
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func Topla(a, b int) int { return a + b }
func ikiKat(n int) int { return n * 2 }
func main() {
fmt.Println(Topla(2, 3), ikiKat(4))
}Expected output
5 8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Can two files in the same package see each other's definitions?
- No, only the exported ones
- Only those in the same file
- Yes, all definitions Correct answer
- Only the upper-case ones
Explanation: All definitions in the same package are visible across files.
2 Same package
The string_utils.go and number_utils.go files:
____ utils
The string_utils.go and number_utils.go files:
package utils
Explanation: The same package declaration makes files one package.
3 Visibility matching
| Term | Meaning |
|---|---|
Println |
Exported |
print |
Package-private |
fmt.Println |
External access |
hello |
Lowercase |