What are Packages?
In Go, packages are the fundamental way to organize and structure your code. Every Go source file belongs to a package, and programs are built by linking packages together.The Main Package
Every executable Go program must have exactly onemain package with a main() function as the entry point:
Organizing Code Across Multiple Files
Files in the same package can access each other’s functions and variables. All files in the same directory with the same package declaration are considered part of the same package.Define functions in separate files
Functions defined in one file are accessible from other files in the same package.
hey.go
bye.go
main.go
All files in the same package share the same namespace. You cannot declare the same function name twice within a package, even if they’re in different files.
Understanding Scopes
Scope determines where a variable, constant, or function can be accessed in your code. Go has several levels of scope:File Scope
Import statements have file scope - they’re only visible within the file where they’re declared:Package Scope
Declarations at the package level (outside any function) are visible throughout all files in the package:Block Scope
Variables declared inside a function or block are only visible within that block:Nested Scopes
Inner scopes can access outer scopes, but not vice versa:Importing Packages
Basic Import
To use code from another package, you must import it:Multiple Imports
You can import multiple packages using either syntax:Renaming Imports
If you have naming conflicts or want to shorten package names, you can rename imports:Exported vs Unexported Names
Go controls visibility across packages using capitalization:- Exported (public): Names that start with an uppercase letter can be accessed from other packages
- Unexported (private): Names that start with a lowercase letter are only accessible within their own package
Best Practices
- Keep packages focused: Each package should have a clear, single purpose
- Use descriptive package names: Package names should be short, lowercase, and descriptive
- Avoid circular dependencies: Package A should not import package B if B imports A
- Minimize package scope: Declare variables at the smallest scope necessary
- Use unexported names by default: Only export what needs to be public API
Common Patterns
Package-level constants and variables
Grouping related functionality
Understanding packages and scopes is fundamental to writing clean, maintainable Go code. They help you organize your codebase and control how different parts of your program interact.