Importing Packages
Basic Import Syntax
The import keyword, followed by a package's import path in quotes, makes that package's exported identifiers available, accessed with a dot after the package's name (usually the last element of its path).
Example: Basic Import Syntax
package main
import "fmt"
func main() {
fmt.Println("fmt package imported and used")
}
Login to try C/C++/Java/PHP code in the editor
Grouped Imports
When importing several packages, Go convention groups them in one parenthesized block rather than repeating the import keyword on each line, which gofmt keeps neatly sorted.
Note: Run 'go fmt' to automatically keep grouped imports sorted alphabetically.
Example: Grouped Imports
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.ToUpper("go imports"))
}
Login to try C/C++/Java/PHP code in the editor
Aliasing an Import
An import can be given a different local name by placing an identifier before its path, useful when two imported packages would otherwise share the same default name.
Example: Aliasing an Import
package main
import (
"fmt"
str "strings"
)
func main() {
fmt.Println(str.ToLower("ALIASED IMPORT"))
}
Login to try C/C++/Java/PHP code in the editor
Blank Imports for Side Effects
Prefixing an import path with _ imports it purely for its side effects (like an init() function registering something), without making its identifiers usable or triggering an 'unused import' error.
Example: Blank Imports for Side Effects
package main
import (
"fmt"
_ "strings" // blank import: runs init side effects only, not actually needed here
)
func main() {
fmt.Println("blank imports run side effects without exposing identifiers")
}
Login to try C/C++/Java/PHP code in the editor
- Leaving an unused import in a file, which is a compile-time error in Go, not just a lint warning.
- Forgetting to prefix imported identifiers with the package name, e.g. calling Println() instead of fmt.Println().
- Importing a package purely for its side effects without using the blank identifier (_) prefix, causing an 'imported and not used' error.
- import "path" brings a package into scope, accessed via its package name as a prefix.
- Multiple imports are grouped in a single parenthesized import block by convention.
- An unused import is a compile-time error, keeping import lists always accurate.
- A blank import, _ "path", runs a package's init() side effects without exposing its identifiers.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: