0
0
Goprogramming~30 mins

Module initialization in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Module Initialization in Go
📖 Scenario: You are creating a simple Go program that uses a package with an init function. This function runs automatically when the program starts, before the main function.This helps set up things like configuration or initial messages.
🎯 Goal: Build a Go program with a package that has an init function which prints a welcome message automatically when the program starts.
📋 What You'll Learn
Create a package called greetings with an init function
The init function should print "Welcome to the Greetings package!"
Create a main package that imports greetings
The main function should print "Main function started."
💡 Why This Matters
🌍 Real World
Many Go programs use <code>init</code> functions to prepare configuration, logging, or database connections automatically when the program starts.
💼 Career
Understanding module initialization is important for writing clean, maintainable Go code and working with packages in professional software development.
Progress0 / 4 steps
1
Create the greetings package with an init function
Create a package called greetings. Inside it, write an init function that prints "Welcome to the Greetings package!" using fmt.Println. Import the fmt package.
Go
Hint

The init function has no parameters and no return values. It runs automatically when the package is loaded.

2
Create the main package and import greetings
Create a package called main. Import the greetings package you created earlier. Also import fmt for printing.
Go
Hint

Use parentheses to import multiple packages. The greetings package must be imported to trigger its init function.

3
Add the main function to print a start message
In the main package, write a main function that prints "Main function started." using fmt.Println.
Go
Hint

The main function is the program's entry point. Use fmt.Println to print the message.

4
Run the program and observe the output
Run the Go program. It should first print "Welcome to the Greetings package!" from the init function, then "Main function started." from the main function. Write a print statement to display the output of the program.
Go
Hint

When you run the program, the init function runs before main. The output shows both messages in order.