Introduction to Variable Scope: Local and Package-Level Variables in Go
Introduction to Variable Scope: Local and Package-Level Variables
Welcome back! We are advancing swiftly to another significant terrain: variable scope in Go. You've already learned how to create and call functions, as well as how to incorporate return statements. Now, we move to one of the crucial aspects of functions — understanding the scope of variables both within and outside of these functions. Are you thrilled to dive in? We guarantee it's going to be enlightening!
Understanding Local and Package-Level Variables
In Go, a variable defined within a function has a scope confined to that function, making it a local variable. This simply means that you cannot access a local variable outside the function in which it's declared.
What happens if we want a variable that is accessible across functions within the same package? That's where package-level variables come in! Package-level variables are those defined outside any function and are accessible throughout your code — both inside and outside functions within the same package.
Let's step through an example to illustrate:
Here, chosenCountries is a package-level variable. We are able to append a new country to our slice within the function addCountry(). After invoking addCountry() with "Spain," we printed chosenCountries and found its value to be ["France", "Italy", "Spain"].
Trying to Access a Variable Not in Scope
Attempting to access a variable that is not within your current scope is a common mistake. This occurs when you try to access a local variable outside the function in which it is defined.
Consider this example:
Running this code will result in a compilation error because destination is not declared in the package scope. Go enforces scope rules to maintain clarity and prevent unexpected alterations to data.
