package and import
- Go course
- Beginner
- Lesson 8/90
- 4 min
Learn the package declaration and adding packages with import.
package and import
Every .go file starts with a package declaration. It tells which package the file belongs to. Executable programs use package main; libraries use their own name.
The import keyword brings other packages into scope. A single package uses import "fmt"; multiple packages use a parenthesised block.
Importing a package you do not use is a compile error; Go enforces this strictly.
Multiple import block
To import multiple packages you use a parenthesised block:
import (
"fmt"
"os"
)
Each package sits on its own line. The package path is wrapped in double quotes. Go treats imported but unused packages as a compile error.
Standard library packages are imported with short names like fmt, os, strings. Third-party packages use their full path (e.g. github.com/...).
Practice Multiple imports
Import the fmt and strings packages with a parenthesized import block. Print the result of strings.ToUpper("go") with fmt.Println.
Starter code
package main
// importları buraya yaz
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.ToUpper("go"))
}Expected output
GO
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which package does an executable Go program use?
- package main Correct answer
- package app
- package exe
- package run
Explanation: Executable programs use package main.
2 Importing
To import the fmt package:
____ "fmt"
To import the fmt package:
import "fmt"
Explanation: the import keyword imports a package.
3 Match the declarations
| Term | Meaning |
|---|---|
package main |
Executable |
package utils |
Library |
import "fmt" |
Opens package |
package fmt |
Standard package |