ProgramGuru

Importing Packages

Start with Importing Packages

The import declaration makes another package’s exported API available in the current source file.

What you’ll learn

  • Explain the main purpose of importing packages.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Multiple imports are normally grouped in parentheses and formatted by gofmt or goimports. You can use an import alias, for instance text "strings", when its ordinary package name conflicts with a local identifier.

Go rejects unused imports. A blank import _ "path" is a special case for deliberately importing package initialization effects; beginners should not use it to hide an unused-import error.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for importsAliases change local references, not package implementations.import strings as textStep 1Call text.TrimSpaceStep 2Call text.ToUpperStep 3Print resultStep 4Aliases change local references, not package implementations.
Aliases change local references, not package implementations.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"fmt"
	text "strings"
)

func main() {
	title := text.TrimSpace("  Go tools  ")
	fmt.Println(text.ToUpper(title))
}

Output

GO TOOLS

Trace what the program does

The alias text names the strings package inside this file. TrimSpace removes leading and trailing spaces, ToUpper capitalizes the result, and fmt prints GO TOOLS.

Avoid common mistakes

  • Imports must be used in the file that declares them; imports in another file are not automatically available.
  • Use blank imports only when you intentionally require initialization side effects.

Try it yourself

Give fmt a local alias and print a string created with strings.Repeat.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What does an import alias change?
Choose one answer. You can try again.

Answer and explanation

The local name used for that package in the importing file

Correct. The alias text names the strings package inside this file.

What you should remember

You have practiced Importing Packages in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Exported and Unexported Identifiers →