← Back to Go Course | Chapter 10: Packages & Modules | Lesson 2 of 6

Importing Packages

Importing a package is like borrowing a specific set of tools from someone else's toolbox and bringing them into your own workspace so you can use them.

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

markup
package main

import "fmt"

func main() {
	fmt.Println("fmt package imported and used")
}

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

markup
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.ToUpper("go imports"))
}

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

markup
package main

import (
	"fmt"
	str "strings"
)

func main() {
	fmt.Println(str.ToLower("ALIASED IMPORT"))
}

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

markup
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")
}
Common Mistakes
  1. Leaving an unused import in a file, which is a compile-time error in Go, not just a lint warning.
  2. Forgetting to prefix imported identifiers with the package name, e.g. calling Println() instead of fmt.Println().
  3. Importing a package purely for its side effects without using the blank identifier (_) prefix, causing an 'imported and not used' error.
Chapter Summary
  • 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.