Packages and Imports
Every Go file starts with a package declaration. A package is the unit for grouping code: all the .go files in one folder must use the same package name, and they can use each other's functions, types, and variables without any import.
package main
The main package is special
package main+func main()= a program you can run (it produces an executable file).- A package with any other name (for example
package kasir) is a library: its code is used by other packages and can't be run on its own.
Imports
To use code from another package, import it by its path. After that, access its contents through the package name (the last part of the path):
import (
"fmt"
"math/rand" // path "math/rand", dipakai sebagai rand.Intn(...)
"strings"
)
So the package at path math/rand is used as rand.Intn(...). A few import rules:
- An unused import is a compile error, just like an unused local variable.
- You can give a package an alias if its name clashes or is too long:
import str "strings", then callstr.ToUpper(...). - An import with
_(import _ "image/png") only runs the package's initialization without using its name. You'll rarely need this as a beginner.
Your own packages
In a real project, code is split across several folders. Here's an example structure for a cashier app:
kasir/
├── go.mod module github.com/rina/kasir
├── main.go package main
└── diskon/
└── diskon.go package diskon
// diskon/diskon.go
package diskon
func Hitung(harga, persen int) int {
return harga * persen / 100
}
// main.go
package main
import (
"fmt"
"github.com/rina/kasir/diskon" // path = nama module + nama folder
)
func main() {
fmt.Println(diskon.Hitung(50000, 10)) // 5000
}
The import path of your own package always starts with the module name from go.mod (covered two lessons from now), followed by the folder name. The Go runtime on this platform only runs a single main.go file, so the exercises in this chapter stay in one file, but the structure above is what you'll use in a real project.
Try it yourself
The editor holds an example that uses a few standard packages, including an alias. Run it, then try deleting one of the str. uses and watch for the imported and not used error if that package is no longer used.