Go Lang – Variables
A variable is usually a placeholder of information that can be used later in the program. For declaring variables, we need to follow certain rules.
Rules for naming variables:
- Variables names must begin with a letter or an underscore(_)
- Variable name should not start with a digit
- The name of the variables is case-sensitive.
- Keywords cannot be used as a variable name.
- For declaring a variable,
- Explicitly declare data type
- Assign value without declaring type
- Shorthand notation( :=)
Declaring Variables:
we can declare varibales using 2 ways:
- With “Var” keyword.
- With “:=” sign
Example:
- var nam = “John”
- x :=2
The only difference between the 2 method of declaring variables is in first method, we can declare the variable and can assign the values later. But in the second method, declaration and assignment cannot be done separately.
we can also declare multiple variables in the same line.
Ex:
var a,b,c,d = 1,2,3,4.
c, d := 7, “Pheonix”
Conclusion:
In this blog, we learned about how to declare variables in Golang and its naming rules.