Variables in Go

Variables in go can be declared using following syntax
var <variable-name> <data-type> = <value>
For e.g.
package main
func main(){
var x int = 40
}
There is also a shortcut of defining variables
package main
func main(){
x := 10
}
In the above case, we have used the :=
operator which is the shortcut method to declare variables. You don’t need to write var
neither do you need to write the type
. The type is inferred from the value. Basically whatever value is, the type is assigned accordingly.
package main
import (
"reflect"
"fmt"
)
func main(){
x := 10
y := "I am a string"
fmt.Println(reflect.TypeOf(x), reflect.TypeOf(y))
}
In the above example, we have imported the reflect package which is a standard built-in package for go. Using reflect, we can determine the type of x and y. You will notice x will be int and y will be string.
Defining Variables in Bulk
package main
import "fmt"
func main(){
var (
c = 10
d = 20
e = 30
)
fmt.Println(c, d, e)
var (
f int
g int
h int
)
fmt.Println(f, g, h)
var i, j, k int
i = 1
j = 2
k = 3
fmt.Println(i, j, k)
var l, m, n int = 4, 5, 6
fmt.Println(l, m, n)
o, p, q := 1, 2, 3
fmt.Println(o, p, q)
}
In the above example, we are declaring and initializing variable c, d, e at once. We are declaring f, g, h and initializing them later. Similarly we are declaring i, j, k once with combining their types, basically all three will have same int
type. Then we are declaring and initializing l, m, n at once. At the end, we are using shortcut method to declare o, p, q. These are different ways to define variables.
Constants
Go supports constants
const x int = 5
Constants cannot be defined using :=
and they need const
keyword.
Subscribe to my newsletter
Read articles from Sankalp pol directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
