Short Variable Declaration (:= Operator) in GoLang

The usage of variables is essential in any programming language. In this post, we will use the shorthand syntax of declaring variables in Go.

Variable declarations in Go

There are multiple ways of declaring variables. The shorthand syntax allows us to declare and initialize the variable both at the same time. This not only reduces code but creates concise syntax. First, let’s see the regular syntax of declaring variables.

var variableName variableType

Now, we can assign a value to it of type variableType.

The shorthand syntax merges two steps into one. Below is the syntax.

variableName := initialValueOfTheVariable

The operator above (:=) is called the short declaration operator.

Type inferencing

After declaring a variable with the short declaration syntax the variable gets a type. So, if it is reassigned to another type then it throws an error.

package main

import (
	"fmt"
)

func main() {
	a := 42
	fmt.Println(a)
	a = "Hi" // cannot use "Hi" (type string) as type int in assignment
}

The variable type gets inferred by the Go compiler after the declaration happens so it cannot be reassigned with a new type.

Declaring multiple variables

Multiple variables can be declared using the shorthand syntax of variable declaration. To declare multiple variables, the order should be maintained on both sides of the operator. The declaration below shows that.

var1, var2, var3, ... := value1, value2, value3, ...

Declaring functions

Functions can be declared with the same short syntax as well. Go has great support for functions and allows support anonymous functions in Go code. The code below shows how to declare functions using the shorthand syntax.

package main

import (
	"fmt"
)

func main() {
	// declare the function
	f := func() {
		fmt.Println("Inside a function")
	}
	
	// call using the name
	f()   // Inside a function
}

Advantages of short declaration

The short declaration of variables has some advantages. It enables the code to be short and concise. Also, it stops assigning wrong types to a variable.

A function can return multiple values in Go. So, in that case, multiple assignments can be made easily. Error handling is a use case of this particular type.

Drawbacks of short declaration

The short declaration has some drawbacks also. It cannot be used in the Global scope. It must be inside a function. To declare outside the function scope var, const, func must be used accordingly.