When we first start with Go, the main function seems almost too simple. A single entry point, a straightforward go run main.go and voila - our program isup and running.
But as we dug deeper, I realized there’s a subtle, well-thought-out process churning behind the curtain. Before main even begins, the Go runtime orchestrates a careful initialization of all imported packages, runs their init functions and ensures that everything’s in the right order - no messy surprises allowed.
The way Go arranges has neat details to it, that I think every Go developer should be aware of, as this influences how we structure our code, handle shared resources and even communicate errors back to the system.
Let’s explore some common scenarios and questions that highlight what’s really going on before and after main kicks into gear.
Picture this: you’ve got multiple packages, each with their own init functions. Maybe one of them configures a database connection, another sets up some logging defaults and a third initializes a lambda worker & the fourth initializing an SQS queue listener.
By the time main runs, you want everything ready - no half-initialized states or last-minute surprises.
Example: Multiple Packages and init Order
// db.go package db import "fmt" func init() { fmt.Println("db: connecting to the database...") // Imagine a real connection here } // cache.go package cache import "fmt" func init() { fmt.Println("cache: warming up the cache...") // Imagine setting up a cache here } // main.go package main import ( _ "app/db" // blank import for side effects _ "app/cache" "fmt" ) func main() { fmt.Println("main: starting main logic now!") }
When you run this program, you’ll see:
db: connecting to the database... cache: warming up the cache... main: starting main logic now!
The database initializes first (since mainimports db), then the cache and finally main prints its message. Go guarantees that all imported packages are initialized before mainruns. This dependency-driven order is key. If cache depended on db, you’d be sure db finished its setup before cache’s init ran.
Now, what if you absolutely need dbinitialized before cache, or vice versa? The natural approach is to ensure cache depends on db or is imported after db in main. Go initializes packages in the order of their dependencies, not the order of imports listed in main.go. A trick that we use is a blank import: _ "path/to/package" - to force initialization of a particular package. But I wouldn’t rely on blank imports as a primary method; it can make dependencies less clear and lead to maintenance headaches.
Instead, consider structuring packages so their initialization order emerges naturally from their dependencies. If that’s not possible, maybe the initialization logic shouldn’t rely on strict sequencing at compile time. You could, for instance, have cache check if db is ready at runtime, using a sync.Once or a similar pattern.
Imagine a scenario where packages A and B both depend on a shared resource - maybe a configuration file or a global settings object. Both have initfunctions and both try to initialize that resource. How do you ensure the resource is only initialized once?
A common solution is to place the shared resource initialization behind a sync.Once call. This ensures that the initialization code runs exactly one time, even if multiple packages trigger it.
Example: Ensuring Single Initialization
// db.go package db import "fmt" func init() { fmt.Println("db: connecting to the database...") // Imagine a real connection here } // cache.go package cache import "fmt" func init() { fmt.Println("cache: warming up the cache...") // Imagine setting up a cache here } // main.go package main import ( _ "app/db" // blank import for side effects _ "app/cache" "fmt" ) func main() { fmt.Println("main: starting main logic now!") }
Now, no matter how many packages import config, the initialization of someValuehappens only once. If package A and B both rely on config.Value(), they’ll both see a properly initialized value.
You can have multiple init functions in the same file and they’ll run in the order they appear. Across multiple files in the same package, Go runs init functions in a consistent, but not strictly defined order. The compiler might process files in alphabetical order, but you shouldn’t rely on that. If your code depends on a specific sequence of init functions within the same package, that’s often a sign to refactor. Keep init logic minimal and avoid tight coupling.
Legitimate Uses vs. Anti-Patterns
init functions are best used for simple setup: registering database drivers, initializing command-line flags or setting up a logger. Complex logic, long-running I/O or code that might panic without good reason are better handled elsewhere.
As a rule of thumb, if you find yourself writing a lot of logic in init, you might consider making that logic explicit in main.
Go’s main doesn’t return a value. If you want to signal an error to the outside world, os.Exit() is your friend. But keep in mind: calling os.Exit() terminates the program immediately. No deferred functions run, no panic stack traces print.
Example: Cleanup Before Exit
db: connecting to the database... cache: warming up the cache... main: starting main logic now!
If you skip the cleanup call and jump straight to os.Exit(1), you lose the chance to clean up resources gracefully.
You can also end a program through a panic. A panic that’s not recovered by recover() in a deferred function will crash the program and print a stack trace. This is handy for debugging but not ideal for normal error signaling. Unlike os.Exit(), a panic gives deferred functions a chance to run before the program ends, which can help with cleanup, but it also might look less tidy to end-users or scripts expecting a clean exit code.
Signals (like SIGINT from Cmd C) can also terminate the program. If you’re a soldier, you can catch signals and handle them gracefully.
Initialization happens before any goroutines are launched, ensuring no race conditions at startup. Once main begins, however, you can spin up as many goroutines as you like.
It’s important to note that main function in itself runs in a special “main goroutine” started by the Go runtime. If main returns, the entire program exits - even if other goroutines are still doing work.
This is a common gotcha: just because you started background goroutines doesn’t mean they keep the program alive. Once main finishes, everything shuts down.
// db.go package db import "fmt" func init() { fmt.Println("db: connecting to the database...") // Imagine a real connection here } // cache.go package cache import "fmt" func init() { fmt.Println("cache: warming up the cache...") // Imagine setting up a cache here } // main.go package main import ( _ "app/db" // blank import for side effects _ "app/cache" "fmt" ) func main() { fmt.Println("main: starting main logic now!") }
In this example, the goroutine prints its message only because main waits 3 seconds before ending. If main ended sooner, the program would terminate before the goroutine completed. The runtime doesn’t “wait around” for other goroutines when main exits. If your logic demands waiting for certain tasks to complete, consider using synchronization primitives like WaitGroup or channels to signal when background work is done.
If a panic happens during init, the whole program terminates. No main, no recovery opportunity. You’ll see a panic message that can help you debug. This is one reason why I try to keep my init functions simple, predictable and free of complex logic that might blow up unexpectedly.
By the time main runs, Go has already done a ton of invisible legwork: it’s initialized all your packages, run every init function and checked that there are no nasty circular dependencies lurking around. Understanding this process gives you more control and confidence in your application’s startup sequence.
When something goes wrong, you know how to exit cleanly and what happens to deferred functions. When your code grows more complex, you know how to enforce initialization order without resorting to hacks. And if concurrency comes into play, you know that the race conditions start after init runs, not before.
For me, these insights made Go’s seemingly simple main function feel like the tip of an elegant iceberg. If you have your own tricks, pitfalls you’ve stumbled into, or questions about these internals, I’d love to hear them.
After all, we’re all still learning - and that’s half the fun of being a Go developer.
Thanks for reading! May the code be with you :)
My Social Links: LinkedIn | GitHub | ? (formerly Twitter) | Substack | Dev.to
For more content, please consider following. See ya!
The above is the detailed content of A Peek Behind Go's Entry Point - From Initialization to Exit. For more information, please follow other related articles on the PHP Chinese website!