Go Packages
A package is a group of source files that share one package name. A program imports packages to use the names they provide.
Two Single Imports
This program imports fmt and strings on separate lines. Both packages do work in main.
package main
import "fmt"
import "strings"
func main() {
fmt.Println(strings.ToUpper("go"))
fmt.Println(strings.ToLower("CODE"))
}The Math Package
The math package holds number helpers. Max picks the larger value, and Sqrt finds a square root.
package main
import "fmt"
import "math"
func main() {
fmt.Println(math.Max(3, 7))
fmt.Println(math.Sqrt(16))
}A Grouped Import Block
One import block can hold several packages. Each package sits on its own line in the block.
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Contains("packages", "pack"))
}An Unused Import Fails
The strings package is imported but never used. The compiler refuses the program.
package main
import "fmt"
import "strings"
func main() {
fmt.Println("Hello")
}Example
package main
import (
"fmt"
"math"
"strings"
)
func main() {
fmt.Println(strings.ToUpper("go tools"))
fmt.Println(math.Sqrt(25))
fmt.Println(strings.Count("banana", "a"))
}Key points
- Package: a group of source files that share one package name.
- Use import to bring a package into a program.
- A name that starts with a capital letter is exported.
- An exported name can be used outside its package.
- A name that starts with a small letter stays inside its package.
- Write several imports in one grouped block with parentheses.
- Every imported package must be used, or the program does not compile.
In this example, one grouped block imports fmt, math, and strings. The strings package turns the text into capitals on the first line. The math package finds the square root of 25 on the second line. The last line counts the letter a in banana, which is 3.
Note
The package name is the last part of its import path.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Exercise
A program imports the strings package but never uses it. What happens?