Introduction
One of the first things or concepts or syntax you have to learn when trying to grasp a programming language is variables.
As simple as it may sound variables are what hold a programming language together. Just like fuel is to a combustion engine. Variables are the needed power to get any programming language going.
I do not know about you but whenever I try to learn a programming language and for reason I struggle with variables.
Understanding the syntax for variable declaration and initialization always seems to elude me but the goal of this article is to help you navigate and comprehend the concept of variables in Golang and hopefully get you started to Golang mastery 😉.
Strap In and let the ride begin.
The Building Blocks of Golang Programs
You know those individual Lego pieces you put together to create a house or whatever your imagination can come up with.
Let me ask you a question. Without those individual pieces carefully put together would you be able to build a Lego house?
I guess not.
The same goes for variables in any programming language. Without variables in programming languages, I do not think all the beautiful and life-changing solutions we have in our world today would have existed.
func main () {
var age int
age = 30
fmt.Println(age) // this will print 30
}
Remember I said I struggled to understand what a variable is when I started learning my first programming language. This is the analogy that helped me never to struggle to understand variables again.
Think of variables as a simple container. You see that jar of peanut butter or the bottle of instant coffee in your pantry. Yeah, there are variables. Whenever you need peanut butter all you need do is to get the jar and what you seek in sitting pretty in the jar.
The same goes for variables, you use them to keep something in it and when you need it all you need do is to get the variable.
Variable Types
Why do I keep using peanut butter for my analogy 🧐 . I don’t know but if you love peanut butter like I do say so in the comment.
Just like you have different flavors of peanut butter from crunchy to spicy, variables in Golang also come in different flavors and spice levels.
Below are some of the flavours of variables in Golang
Integers e.g 1,2,3
Floats e.g 0.1, 0.2, 0.3
String e.g Peanut butter sighs not again
Booleans e.g. True or False, on or off.
To get variables up and rolling in Golang we employ the var keyword. This is like an announcement to our Golang programs we have a new kid on the block.
Here is how you do it
var name string
I know I know I say the var keyword I did not say anything about the other words you are seeing “name” and “string”. They are just here to tell your Golang program that there is a container with the identifier “name” and its contents are “string” data type.
Variables are like newborns and require nourishment to thrive. The nourishment comes from initialization. Another new word. Do not worry you will understand all of this.
The assignment operator serves as the passage of nourishment to our variables
var name string = "nourishment"
Initialization and usage
Initialization is the act of giving our Golang variables something to hold.
var name string = "Idris Elba"
Above I just declared and initialized a variable. The assignment operator = our trusty and ever-ready tool for the infusion.
Imagine you are at a gas station trying to refuel your car. The nozzle you dip into the opening of your car tank to deliver the fuel can be likened to an assignment operator.
Scope: Boundaries of accessibility
Golang variable scope rules are the concept that defines the accessibility of variables within your Golang programs.
Think of two countries country A and country B. In country A it is illegal to wake up by 4 am while in country B it is illegal to go to bed at 10 pm.
Say you live in country A and you moved to country B. Would you say the law in country A that makes waking up by 4 am still applies to country B ? No right.
Variables in Golang also have rules governing them. Look at the below code blocks
var globalVariable string = "This is a global variable."
func main() {
localVariable := "This is a local variable."
fmt.Println(globalVariable) // This will print "This is a global variable."
fmt.Println(localVariable) // This will print "This is a local variable."
}
In the code block above, globalVariable is a global variable because it is declared outside of any function. This means that it can be accessed from anywhere in the program. localVariable is a local variable because it is declared inside of the main function. This means that it can only be accessed from within the main function.
Local variables, confined to the scope of a specific function, are like residents within their own countries. They can interact with other variables within the same country but remain inaccessible to the outside world.
Global variables, on the other hand, roam freely across the entire program, like residents with unrestricted access to all countries. They can be accessed from any function within the program, making them powerful but also prone to potential conflicts.
Some advanced concepts
Have you ever been mistaken for someone else? Yeah, we have had those moments. You hear something like you look so much like my childhood friend.
In Golang this is called shadowing, a phenomenon that arises when local variables are given the same name as global variables. You know there is going to be some sort of confusion.
Local variables, when declared within a function, take precedence over global variables with the same name.
var age string
func main() {
var age string // Bad practice
}
To avoid shadowing issues, it is important to choose distinct names for local and global variables, ensuring clear and unambiguous identification.
var age string
func main() {
var newAge string // Good practice
}
Another concept to keep in mind is type inference. This is a clever feature of the Golang compiler and it involves the compiler automatically deducing the variable types based on the initialized values.
Take for instance when you assign an integer value of 24 to a variable, the compiler infers that the variable should be of type int. This feature makes it easy to write code.
func main () {
number := 24 // type inference
}
Type inference is not foolproof. It is a good practice to explicitly declare variable types in your Golang code when clarity is important.
Conclusion
Variables are the bedrock upon which your Golang programs are built. One variable at a time. In this article, we have gone over a few concepts like variable types, initialization, usage, and accessibility.