What is a short variable declaration in Go?

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.

Short variable declaration

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 main
import "fmt"
func main() {
//declaring a variable with the var keyword
var num1 int
//declaring a variable with an initial value
var num2 int = 1
fmt.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 main
import "fmt"
func main() {
// short variable declaration for implicit int data type
num1:= 1
//declaration for implicit string data type
my_str:= "Hello there!"
//multiple variables initialised using short declaration
a,b,c:= 11,15,20
fmt.Println(num1, my_str, a,b,c)
}

Free Resources