Limited Offer
60% OFF on all plans!

Packages and Imports in Go

Learn how Go organizes code into packages, how to import standard library and custom packages, and how visibility (exported vs unexported) works.

What is a Package

Every Go source file belongs to exactly one **package**. The first line of a file is `package name`; all files in the same directory must declare the same package name. Code in the `main` package can be built into an executable. Other packages are libraries that you import and use.

1. Package Declaration

First line of every file.

2. One Package per Directory

All .go files in a directory share one package.

Import Syntax

Use the `import` keyword to bring in other packages. You can list one import per line, group them in parentheses, or use an **alias** to refer to a package by a different name. The blank identifier `_` imports a package only for its side effects (e.g. `init()`).

1. Grouped and Single Imports

Parenthesized list or single import.

2. Import Alias

Refer to a package by another name.

Modules and Import Paths

Go code lives inside a **module**, defined by a `go.mod` file. The **module path** (e.g. `example.com/myapp`) is the prefix for all import paths in that module. Standard library packages use short paths like `"fmt"`; your own packages use the module path plus the directory, e.g. `example.com/myapp/mypkg`.

1. go.mod and Module Path

Module declaration and import paths.

The go.mod File and Go Commands

The `go.mod` file defines your module: its path, the Go version, and the list of dependencies. Use `go mod tidy` to sync `go.mod` with the code (add missing deps, remove unused ones). Use `go get` to add or update a package; to remove a package, delete its imports and run `go mod tidy`.

1. Structure of go.mod

module, go version, and require directives.

2. go mod tidy

Sync go.mod with your code.

3. Installing and Updating Packages (go get)

Add or upgrade a dependency.

4. Removing (Uninstalling) a Package

Stop using a dependency and clean go.mod.

Exported and Unexported Names

Names that start with an **uppercase** letter are **exported**: they are visible to other packages that import this one. Names that start with a **lowercase** letter are **unexported**: they are visible only inside the same package.

1. Capitalization Rules

Upper = exported, lower = package-private.

Package init and Package-Level Variables

Package-level variables are initialized before any function runs. If a package defines an **init** function, the Go runtime calls it automatically when the package is loaded (after package-level variables are initialized). Use `init` for one-time setup; keep it simple and avoid heavy logic.

1. init Function

Called automatically when the package is loaded.