Variables
Today's blog is about variables in Golang. Variables are a crucial part and a building block of any programming language. Along with variables, there is something called data types (which we also see later in this article) which tells us what type of data a variable is holding. So let us start our discussion by talking about what are variables?
What are variables?
Variables are a named space in memory where we can store data to be used in our applications. They are used to store data required during our application's execution.
var a int = 42
var b bool
salary := 12.2
So these are some of the examples of variables. Every variable has three parts:-
- Data Type
- Variable name
- Variable value
First, let's understand what each part is.
Data Types
So, what is data type?
Data types tell us what type of value or data a variable is holding. In layman's terms, whether the data stored in the variable is a numeric type of data, a text, etc.
In the above code sample, we saw that there is a value 42 which is a numeric value, there are values that are either true or false (called boolean), etc. These are the types of data the variable is holding.
Examples of some data types present in Go - int, float, bool, int8, int16, etc.
Variable name
Variable names are the names by which we refer to data that is stored in memory and is assigned to variables. So basically it is a way to reach out to that location in memory where the data we want is stored.
In the above example a, b, and salary are some examples of variable names.
Though, there are some rules for naming a variable:-
- A variable name must start with a letter or an underscore character (_)
- A variable name cannot start with a digit
- A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )
- Variable names are case-sensitive (age, Age, and AGE are three different variables)
- There is no limit on the length of the variable name
- A variable name cannot contain spaces
- The variable name cannot be any Go keywords
Valid names - salary, a, age, down, UP, Button, YourWish, List1, mymodel, , etc.
Invalid names - 1, 23length, func, name&age, etc.
Variable values
These are pretty obvious to understand; whatever value a variable holds is that variable's value. It can be of any data type present in Go.
Let us look at all the ways present in Go for declaring and initializing a variable.
Variable Declaration and Initialization
Variable Declaration is telling the Go compiler things like data type, name, etc about variables. So, that it can assign memory to it and return a reference pointing to that memory location.
Variable Initialization is assigning an initial value to the variables. By default, if no value is assigned to a variable in Go then Go itself may assign a value which is called zero value to the variable depending on its type. For eg. - the zero value for int is 0, for boolean is false, etc.
Ways to declare and initialize variables:-
- Using var keyword:
Syntax:
var var_name var_type = var_value
// Or
var var_name var_type
Examples:
var age int = 20
var a float32
var isEligible bool = false
- Using the short variable declaration operator(:=)
Syntax:
var_name := var_value
Examples:
price := 12
wantSomething := true
I := 0
This is one example of Go's simplicity and its feature of dynamic typing. Using this syntax we don't need to declare the type of variable. Go decides that on its own.
Note - We have to assign an initial value for variables when using this syntax. It is compulsory.
When to use which format?
Use var keyword variables if:-
- you want to avoid initializing the variable.
- you want more control over the type of variable. Since using the short variable declaration operator method Go will assume int data type of a variable if we pass an integer value but you might be interested in an unsigned int or int8 or int16 data type. So for this control, we have to use the var keyword method.
Use the short variable declaration operator (:=) method if you want to avoid declaring the type of variable and take advantage of the Go dynamic typing feature and do not want any specific control over typing of a variable.
Variables at the package level
- These are variables that are available throughout the package and declared outside any function block; at the package level.
For eg. -
package main
import "fmt"
var i int = 0
var j int = 1
var run bool = true
func main() {
fmt.Println(i)
fmt.Println(j)
fmt.Println(run)
}
Output:-
0
1
true
We cannot use the short variable declaration operator syntax to declare these variables.
But we can use variable blocks to keep code clean and concise and also to group similar variables.
So, the above code can be written as:-
package main
import "fmt"
var (
i int = 0
j int = 1
run bool = true
)
func main() {
fmt.Println(i)
fmt.Println(j)
fmt.Println(run)
}
Output:-
0
1
true
Variable Shadowing
- We can not declare the same variable in the same scope more than once.
For eg. this is illegal:-
package main
import "fmt"
func main() {
var i int = 0
var i float32 = 0.0
fmt.Println(i)
}
Error:-
./prog.go:7:6: i redeclared in this block
./prog.go:6:6: other declaration of i
Note - Scope of a variable is like an extent or the block of code for which we can access the variable. After the scope of the variable ends, it is deleted.
Variables declared in functions have local scope. They cannot be accessed outside it and once a function finishes executing they are removed from memory.
Variables declared at package level have package level scope. They are accessible throughout the package.
- However, if a variable is declared at package level and then again in a local scope, it will work and the variable inside the local scope will take precedence. This is called variable shadowing.
For eg. -
package main
import "fmt"
var i int = 123
func main(){
var i float32 = 0.0
fmt.Printf("%v, %T", i, i)
}
Output:-
0, float32
Package Visibility
Go determines if an item is exported and unexported through how it is declared.
If the first letter of the variable, function, etc is lowercase then that item is only visible or available for use in the same package.
If the first letter of the variable, function, etc is uppercase then that item is visible or available for use in the same package as well as outside the package.
For Eg. -
package main
import "fmt"
var I int = 123 // Visible inside and outside package
var j int // Visible only inside the package
func main(){
fmt.Printf("%v, %T\n", I, I)
fmt.Printf("%v, %T", j, j)
}
Output:-
123, int
0, int
- If you have used other Object Oriented Programming Languages like Python, Java, and C/C++, then you may find that this is somewhat similar to access modifiers.
Some Important Points
There is a special type of variable called _ (only an underscore) which will get the value but memory will not be allocated to it. This is used when there is a value we cannot avoid, for eg. from a function; and also there is no use to it too.
Variables declared in local scope that is never used is a compile time error in Golang. This is done to keep the app clean.
Wrap Up
So, with this, we end our discussion on variables in Go. I hope you enjoyed reading this blog and got something out of it. There is more in Go that is to be known which we will see in the future.
Feel Free to comment down below if there are mistakes😊️. Also, you can connect with me on -
LinkedIn - My LinkedIn Handle
Twitter - My Twitter Handle
Github - My Github profile