Go Packages & Modules

What is a Package?

A package is a way to organize and reuse code in Go.

Every Go file belongs to a package.

Loading...
Output:

Built-in Packages

Go provides many built-in packages like fmt, math, and time.

You import them using the import keyword.

Loading...
Output:

Creating Custom Packages

You can create your own packages by placing Go files in a folder.

The package name must match the folder name.

Loading...
Output:

Importing Custom Packages

You can import your custom package using its module path.

Then call exported functions (capitalized names).

Loading...
Output:

Exported vs Unexported

In Go, names starting with a capital letter are exported (public).

Lowercase names are private to the package.

Loading...
Output:

What is a Module?

A module is a collection of packages managed together.

It defines your project and its dependencies.

Loading...
Output:

go.mod File

The go.mod file tracks your module name and dependencies.

It is automatically created when you run go mod init.

Loading...
Output:

Managing Dependencies

Go modules automatically handle external libraries.

Use go get to install packages.

Loading...
Output:

Project Structure Example

A typical Go project is organized using packages and modules.

Loading...
Output:

Why Packages & Modules Matter

They help you organize code and build scalable applications.

  • Reusable code
  • Clean project structure
  • Dependency management

Common Mistakes

Be careful with these:

  • Incorrect import paths
  • Forgetting to export functions (capital letters)
  • Not initializing modules

Practice

Create a custom package with a function and import it into main.

Loading...
Output:

Need Help?