0
0
Goprogramming~15 mins

Package scope rules in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Package scope rules
📖 Scenario: You are creating a simple Go program to understand how variables and functions are accessible within a package.
🎯 Goal: Build a Go program that shows how package-level variables and functions can be accessed inside the same package.
📋 What You'll Learn
Create a package-level variable
Create a package-level function
Access the variable and function inside the main function
Print the results to the console
💡 Why This Matters
🌍 Real World
Understanding package scope is essential for organizing Go programs into reusable and maintainable parts.
💼 Career
Go developers frequently use package-level variables and functions to share data and logic within packages, making this knowledge critical for writing clean and effective Go code.
Progress0 / 4 steps
1
Create a package-level variable
Create a package-level variable called message of type string and set it to "Hello from package scope!".
Go
Hint

Package-level variables are declared outside of any function but inside the package.

2
Create a package-level function
Create a package-level function called getMessage that returns a string and returns the message variable.
Go
Hint

Functions declared outside main() are package-level and can be used anywhere in the package.

3
Access the variable and function inside main
Inside the main function, create a variable called msgFromVar and assign it the value of the package-level variable message. Then create a variable called msgFromFunc and assign it the result of calling the getMessage() function.
Go
Hint

You can use package-level variables and functions directly inside main().

4
Print the results
Add import "fmt" at the top. Inside the main function, print msgFromVar and msgFromFunc each on a new line using fmt.Println.
Go
Hint

Use fmt.Println to print each message on its own line.