Flexibility of defining variables in Golang
Here i wanna share my experience again while using Golang language which i work on right now, is that we have a flexibility to defining a variable in this language.
Strict type of variables
Before we continue to how the variable is defined in Golang, just wanna let you all know that Golang is a — strict type variable — what is that mean?
Meaning that if you define a variable include the variable type, then no way you can change into another type, for example you define variable a as int, then no way that you can re-define in another line of code for variable a into other type, let say string type.
the func ChangeVariableValueWrong() will return error because it assign value to a different type of variables.
Various ways of defining variable in Golang
Here we will explain about various ways of defining a variable in Golang with the correct ways.
Single variable declaration
In here we have a as type int and for this output will be :
Value of a = 0
This because if you initialize for type int, then the initial value is 0.
Declaration with initialization
In here we have variable a and b, and the output will be :
100
One Hundred
After we define the variable type then we can initialize the value directly in one line of code, the pattern is as follow :
var name varType = value
So the output will print the initialized values there
Declaration with type inference
Yes you also can assign any value to the variables, then Golang will conclude what type of variable is this. The output for this code is :
int
string
Golang will then auto assign variable type to the variable based on the value in the variable.
Short variable declaration
The short “:=” is the parameter to assign a value to the variable, no more need var declaration here and Golang will automatic assign the variable type also based on the variable value. The output for this code is :
int
Declaration of multiple variables
Golang allow us to assign multiple values in one line, to make it simpler. The output for this code is :
JohnDoe
6
Mobile - 2000
Universal type of variable
Even Golang is strict type of variable, but they have a magic keyword to make us define a variable without any type, in Golang we can use type interface{} and we can assign value of anything to it.
The output of this code is :
(<nil>, <nil>)
(42, int)
(hello, string)
It explain that in the first line the output is nil, because we haven’t define the variable type to it, but 2nd and 3rd line of output we already define the variable and type there.
for reference you can view here.