Declaration of a variable means specifying the identification of a particular variable, such as its data type, and optionally setting its initial value, which is known as initialization.
In Go, there are two main ways to declare a variable.
In the first method, you can use the var
keyword before the variable name, followed by the data type. This can include an initialization as well.
Let’s look at an example!
package mainimport "fmt"func main() {//declaring a variable with the var keywordvar num1 int//declaring a variable with an initial valuevar num2 int = 1fmt.Println(num1,num2)}
The other, simpler way is to use a :=
statement instead of the var
keyword. You do not need to specify a data type because that is implicitly understood on its own by Go.
Note: Short variable declaration only works within a function.
Let’s look at a few examples of short variable declaration.
package mainimport "fmt"func main() {// short variable declaration for implicit int data typenum1:= 1//declaration for implicit string data typemy_str:= "Hello there!"//multiple variables initialised using short declarationa,b,c:= 11,15,20fmt.Println(num1, my_str, a,b,c)}