0
0
Goprogramming~30 mins

Creating custom packages in Go - Try It Yourself

Choose your learning style9 modes available
Creating custom packages
📖 Scenario: You are building a small Go program that uses a custom package to organize your code better. This is like having a toolbox with different compartments for different tools.
🎯 Goal: Create a custom package named greetings that has a function to return a welcome message. Then use this package in your main program to print the message.
📋 What You'll Learn
Create a package named greetings in a separate file
Inside greetings, write a function WelcomeMessage that returns a string
In the main program, import the greetings package
Call greetings.WelcomeMessage() and print its result
💡 Why This Matters
🌍 Real World
Custom packages help organize code into reusable parts, making programs easier to manage and understand.
💼 Career
Knowing how to create and use packages is essential for writing clean, maintainable Go programs in professional software development.
Progress0 / 4 steps
1
Create the greetings package
Create a file named greetings.go with a package called greetings. Inside it, write a function named WelcomeMessage that returns the string "Hello from the greetings package!".
Go
Hint

Remember to start with package greetings and define a function that returns the exact string.

2
Set up the main program
Create a file named main.go. Write the main package and import the fmt package and your custom greetings package.
Go
Hint

Use import with parentheses to include both fmt and greetings.

3
Call the WelcomeMessage function
Inside the main function, call greetings.WelcomeMessage() and store the result in a variable named message.
Go
Hint

Use := to declare and assign the variable message.

4
Print the welcome message
Use fmt.Println to print the variable message inside the main function.
Go
Hint

Use fmt.Println(message) to show the message on the screen.