Menu
Coddy logo textTech

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.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Create 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:

  1. Parse the first input by splitting on commas to get individual package definitions
  2. For each package definition, split on colons to get the package name and initialization message
  3. Create a global slice called initLog to track initialization messages
  4. Create a function called logInit that takes a package name and message, then adds the formatted message "[INIT] [package_name]: [message]" to the initLog slice
  5. Simulate package initialization by calling logInit for each package in the order they appear in the input
  6. Display the initialization sequence header: "=== PACKAGE INITIALIZATION SEQUENCE ==="
  7. Print each initialization message from the initLog slice
  8. Display the main program header: "=== MAIN PROGRAM EXECUTION ==="
  9. Print: "All packages initialized successfully"
  10. Parse the second input by splitting on commas to get individual operations
  11. For each operation in the main program:
    • Print: "Executing: [operation]"
    • Add a message to the log: "[MAIN] Operation: [operation]"
  12. 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]"
  13. Display the complete log:
    • "=== COMPLETE EXECUTION LOG ==="
    • Print each entry from the complete log (both init messages and main operations)
  14. 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 main function 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

}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow