Sunday, February 8, 2026

Packages

    Profile Pic of Akash AmanAkash Aman

    Updated: February 2026

    Package Fundamentals

    In Go, the package is the fundamental building block of code organization. While modules manage dependencies between projects, packages manage the code within a project.

    The Package Declaration (package <name>)

    Concept: Every .go file must start with a package declaration, which defines the namespace the file belongs to.

    • Setup: All files in a single folder must share the same package name.
    • Behavior: The package name is what other developers use to access your code (e.g., fmt.Println).
    • Why: This creates a clean "workspace." It prevents naming collisions because a function named Calculate() in package math is distinct from Calculate() in package tax.
    go
    // File: math/adder.go
    package math 
    
    func Add(a, b int) int {
        return a + b
    }
    

    Exported vs. Unexported Identifiers (Capitalization)

    Concept: Go uses a simple rule for access control: The first letter of a name determines its visibility.

    • Behavior:

      • Upper Case (Public): Anything starting with a capital letter is Exported (visible outside the package).
      • Lower Case (private): Anything starting with a lower case letter is Unexported (visible only within that specific package).
    • Why: It removes the need for keywords like public, private, or protected. It makes it immediately obvious to any reader whether a function is part of the public API or an internal helper.

    go
    package user
    
    type Account struct {
        Username string // Exported: Accessible everywhere
        password string // Unexported: Only accessible inside package 'user'
    }
    
    func GetUser() {}    // Exported
    func validate() {}   // Unexported
    

    The main Package and Function

    Concept: A special package name that tells the Go compiler: "This is where the program starts."

    • Setup: To create an executable file, you must name your package main and include a func main().
    • Behavior: When you run go build, the compiler looks for package main. If it doesn't find it, it creates a library (archive) instead of an app.
    • Why: It separates "library code" (logic meant to be reused) from "application code" (logic meant to be run).
    go
    package main
    
    import "fmt"
    
    func main() {
        fmt.Println("Hello, World!") // The entry point of your app
    }
    

    Package Initialization (init function)

    Concept: A special function that runs automatically before main() or before any other code in the package is called.

    • Behavior: Each file can have one or more init() functions. They take no arguments and return nothing.
    • Why: Used for setting up state, checking environment variables, or registering drivers (like database drivers) before the application logic begins.
    go
    package config
    
    var APIKey string
    
    func init() {
        // This runs before anything else starts
        APIKey = os.Getenv("API_KEY")
        if APIKey == "" {
            panic("API_KEY is required!")
        }
    }
    

    Workspace Layout & Imports

    Import Aliasing & Blank Imports

    Concept: Customizing how you reference a package or importing it strictly for its side effects.

    • Behavior: * Alias: import m "math" allows you to use m.Add() instead of math.Add().

    • Blank Import (_): import _ "github.com/lib/pq" runs the package's init() functions without making its identifiers available.

    • Why: Aliases solve naming conflicts (e.g., if you have two different template packages). Blank imports are essential for "plugin" architectures like database drivers or image decoders.

    go
    import (
        "fmt"
        crand "crypto/rand" // Alias to avoid confusion with math/rand
        _ "image/png"       // Register PNG decoder via its init() function
    )
    

    Reference Guides

    Quick Layout Rules

    RuleDescriptionImpact
    Folder = PackageOne directory can contain only one package.Keeps folder structures predictable and clean.
    PascalCaseCapitalized names are exported/public.Instant visual cue for API visibility.
    camelCaseLowercase names are internal/private.Protects implementation details from users.
    No CyclesPackage A cannot import B if B imports A.Prevents "Spaghetti Code" and ensures fast compilation.

    Summary Table

    ConceptPurposeDeveloper Impact
    packageNamespaceOrganizes code into logical units.
    ExportingAPI SurfaceDefines what the "outside world" can see.
    mainEntry PointNecessary to create a runnable binary (.exe).
    init()BootstrappingEnsures the environment is ready before logic runs.
    importDependencyBrings in code from other packages or modules.

    © 2026 Akash Aman | All rights reserved