Package Basics
Declaring a Package
Every Go source file begins with 'package name', declaring which package it belongs to. Files sharing a directory and package name form one cohesive unit that can share unexported identifiers between them.
Example: Declaring a Package
package main
import "fmt"
func main() {
fmt.Println("this file belongs to package main")
}
Login to try C/C++/Java/PHP code in the editor
One Package Per Directory
All .go files directly within a single directory must declare the same package name (aside from a special _test package suffix for external test files) -- Go organizes code by directory, not by individual file.
Example: One Package Per Directory
package main
import "fmt"
func main() {
fmt.Println("mathutils/add.go: package mathutils")
fmt.Println("mathutils/subtract.go: package mathutils")
}
Login to try C/C++/Java/PHP code in the editor
package main Is Special
Only package main, combined with a func main(), can be compiled into a standalone executable with 'go build'. Every other package name produces a library meant to be imported, never run directly.
Example: package main Is Special
package main
import "fmt"
func main() {
fmt.Println("Only package main can be built into a runnable binary")
}
Login to try C/C++/Java/PHP code in the editor
- Putting multiple different package names in files within the same directory -- every .go file in one directory must declare the same package name.
- Assuming the package name must match the directory name exactly -- it's conventional, but Go only requires consistency within the directory itself.
- Forgetting that package main is special: only it can produce a runnable binary, everything else builds as a library.
- Every Go file starts with a package declaration grouping it with other files in the same directory.
- All .go files directly inside one directory must share the same package name.
- package main is reserved for producing a runnable executable; other names produce importable libraries.
- Packages are Go's unit of code organization and namespacing.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: