Learn how to organize your code with packages and modules in Go.
Packages and modules help structure your code, make it reusable, and efficiently manage dependencies.
A package is a collection of Go files grouped in the same directory. Hereβs an example of a `mathutils` package:
// File: mathutils/mathutils.go
package mathutils
// Addition adds two numbers
func Addition(a, b int) int {
return a + b
}
After creating a package, you can use it in another file:
package main
import (
"fmt"
"myproject/mathutils"
)
func main() {
result := mathutils.Addition(5, 3)
fmt.Println("Result:", result)
}
Go uses `go mod` to manage external and internal dependencies.
go mod init myproject
The `go.mod` file identifies a Go project as a module.
main.go
and a folder `mathutils`.Result: 8
π Learn more about Go packages and modules:
Official Go Documentationπ Enjoying these exercises? If you find them useful and want to support my work, buying me a coffee would be greatly appreciated! βπ