Skip to main content

How to Import Packages in Go

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Go's standard library is a set of packages: fmt for printing, strings for text, time for dates and many more. A file lists the packages it uses in an import block and then calls their functions through the package name, as in strings.ToUpper.

Syntax​

Syntax
import (
"<package>"
"<other/package>"
)
PartWhat it does
import ( ... )Lists the packages this file uses, one per line.
"<package>"The package's import path, such as "strings" or "encoding/json".
<name>.<Function>How you use it: the last part of the path, a dot and an exported name.

The Go specification: "An import declaration states that the source file containing the declaration depends on functionality of the imported package and enables access to exported identifiers of that package."

The Example​

The example imports fmt and strings and prints a greeting in capitals.

Prerequisites​

  • Go. go run compiles and runs a single file. This guide uses Go 1.27.4.

Step 1: Write the Code​

Create a file named main.go:

main.go, which imports fmt and strings in one block and prints strings.ToUpper("hello, go").

main.go
package main

import (
"fmt"
"strings"
)

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

strings.ToUpper is an exported name: it starts with a capital letter, which is what makes it usable from other packages.

Step 2: Run It​

Terminal
go run main.go
Output
HELLO, GO

A zsh terminal where go run main.go prints HELLO, GO.

The command is the same in zsh, bash and PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Importing a package and not using it"os" imported and not used, and the program doesn't compileRemove the import
Using a package without importing itundefined: stringsAdd it to the import block
Calling a lowercase name from another package, as in strings.toUpperundefined: strings.toUpper (but have ToUpper): only capitalized names are exportedUse the package's exported functions

Troubleshooting​

SymptomLikely causeFix
imported and not usedAn import is left overDelete it; goimports or an editor can do this for you
undefined: <package>The import is missing or misspelledAdd the import with the exact path

FAQ​

Why does Go refuse unused imports?​

Unused imports slow compilation and hide dead code, so Go treats them as errors rather than warnings.

Can I rename a package when importing it?​

Yes: import str "strings" lets you write str.ToUpper.

Conclusion​

List the packages a file needs in an import block and call their exported names as package.Name. Go accepts no unused imports, which keeps every file's dependencies honest.

Additional Resources​