Go — Packages
Package declaration
// math/utils.go
package utils
func Add(a, b int) int {
return a + b
}
func Multiply(a, b int) int {
return a * b
}
Importing packages
package main
import (
"fmt"
"myproject/math"
)
func main() {
fmt.Println(math.Add(3, 4))
}
Package init
package utils
func init() {
fmt.Println("Package initialized")
}
Internal packages
myproject/
├── internal/
│ └── auth/
│ └── auth.go
├── cmd/
│ └── main.go
└── go.mod
Mini Practice
Write Go code that:
- Creates a package with exported functions
- Imports and uses the package
- Uses package init function
- Organizes code with internal packages
Up Next
In the next lesson, you'll learn about Modules — dependency management.
Related Topics
Frequently Asked Questions about Packages
What is Packages in Go?
Packages is a fundamental concept in Go. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Packages?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Packages.
Why is Packages important in Go?
Packages is essential for Go development. Understanding this concept will help you write better code and solve real-world problems more effectively.