The `init` function
Part of the Logic & Flow section of Coddy's GO journey — lesson 56 of 68.
The init function is a special function in Go that runs automatically when a package is imported. Unlike regular functions, you don't call init directly - Go executes it for you during the package initialization process.
Here's how you define an init function:
package mypackage
import "fmt"
func init() {
fmt.Println("Package mypackage is being initialized!")
}The init function has some unique characteristics: it takes no parameters, returns no values, and runs before the main function starts. This makes it perfect for setting up initial state, registering components, or performing one-time setup tasks that your package needs.
When you import a package that contains an init function, you'll see its effects immediately, even if you don't use any of the package's exported functions. This is why the blank identifier import pattern you learned earlier is so useful - it allows you to trigger a package's initialization without directly using its code.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a package initialization system that demonstrates how init functions execute automatically when packages are imported. You'll build a logging system where different packages initialize themselves and track their startup sequence.
You will receive two inputs:
- A string containing package definitions in the format
"package1:message1,package2:message2,package3:message3"(e.g.,"database:Database connection pool initialized,cache:Cache system ready,logger:Logging system started") - A string containing the main program operations in the format
"operation1,operation2,operation3"(e.g.,"start_server,process_requests,shutdown")
Your task is to:
- Parse the first input by splitting on commas to get individual package definitions
- For each package definition, split on colons to get the package name and initialization message
- Create a global slice called
initLogto track initialization messages - Create a function called
logInitthat takes a package name and message, then adds the formatted message"[INIT] [package_name]: [message]"to theinitLogslice - Simulate package initialization by calling
logInitfor each package in the order they appear in the input - Display the initialization sequence header:
"=== PACKAGE INITIALIZATION SEQUENCE ===" - Print each initialization message from the
initLogslice - Display the main program header:
"=== MAIN PROGRAM EXECUTION ===" - Print:
"All packages initialized successfully" - Parse the second input by splitting on commas to get individual operations
- For each operation in the main program:
- Print:
"Executing: [operation]" - Add a message to the log:
"[MAIN] Operation: [operation]" - Display the execution summary:
"=== EXECUTION SUMMARY ===""Packages initialized: [number_of_packages]""Main operations executed: [number_of_operations]""Total log entries: [total_number_of_log_entries]"- Display the complete log:
"=== COMPLETE EXECUTION LOG ==="- Print each entry from the complete log (both init messages and main operations)
- Display the final message:
"Program execution completed - all init functions ran before main"
Use the strings package to split the input strings and the fmt package for formatted output. This challenge demonstrates how init functions execute automatically during package import and always run before the main function, making them perfect for package setup and initialization tasks.
Cheat sheet
The init function is a special function in Go that runs automatically when a package is imported:
package mypackage
import "fmt"
func init() {
fmt.Println("Package mypackage is being initialized!")
}Key characteristics of init functions:
- Takes no parameters and returns no values
- Runs automatically during package initialization
- Executes before the
mainfunction starts - Perfect for setting up initial state and one-time setup tasks
- Triggers even with blank identifier imports
Try it yourself
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
// Global slice to track initialization messages
var initLog []string
func main() {
reader := bufio.NewReader(os.Stdin)
// Read input (bufio handles lines with spaces correctly)
packageDefs, _ := reader.ReadString('\n')
packageDefs = strings.TrimRight(packageDefs, "\r\n")
mainOps, _ := reader.ReadString('\n')
mainOps = strings.TrimRight(mainOps, "\r\n")
// TODO: Write your code below
// 1. Parse packageDefs by splitting on "," to get individual package entries
// 2. For each entry, split on ":" (max 2 parts) to get packageName and message
// 3. Create a logInit(packageName, message string) function that appends
// "[INIT] [packageName]: message" to the global initLog slice
// 4. Display the initialization sequence header and all init log entries
// 5. Display the main execution header and process each operation from mainOps
// - Print "Executing: <op>" for each operation
// - Append "[MAIN] Operation: <op>" to initLog
// 6. Display execution summary (package count, operation count, total log entries)
// 7. Display complete log and final completion message
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors6Idiomatic Go: Sets
The Set Idiom in GoCreating a SetAdding to a SetChecking for MembershipRemoving from a SetIterating Over a SetRecap - Unique Usernames9Packages and Scope
What is a Package?Exported vs UnexportedCreating a Simple PackagePackage AliasingThe Blank Identifier `_`The `init` functionRecap - Building a Utility