What is the difference between := and = in Go language?

Go := and = difference: In this tutorial, we are going to learn the difference between := and =.
Submitted by IncludeHelp, on October 01, 2021

In the Go programming language, the = is known as an assignment operator which is used to assign the value/expression to the left side variable/constant. While := is known as the short variable declaration which takes the following form,

variable_name := expression

The above statement assigns the value and determines the type of the expression. In such kind of declaration, there is no need to provide the type of the value/expression.

So, a short variable declaration (:=) required a value while declaring a new variable.

Consider the below example – demonstrating the difference between = and :=

Example 1:

// Go program to demonstrate the
// difference between = and :=

package main

import (
	"fmt"
)

func main() {
	// Simple declaration & assignment
	var x int = 10

	// Shorthand declaration
	y := 20

	// Printing the values and types of both
	fmt.Printf("x = %T, %v\n", x, x)
	fmt.Printf("y = %T, %v\n", y, y)
}

Output:

x = int, 10
y = int, 20

See the output – the variable x is declared and assigned using the = operator and the variable y is declared and assigned using the := operator. In the first case, the var keyword and type are required while in the second case, the var keyword and type are not required.

Example 2:

// Go program to demonstrate the
// difference between = and :=

package main

import (
	"fmt"
)

func main() {
	// Declare & assign using :=
	x, y, z := 10, 20, 30

	// Printing the types and values
	fmt.Printf("%T, %v\n", x, x)
	fmt.Printf("%T, %v\n", y, y)
	fmt.Printf("%T, %v\n", z, z)

	// Updating the values using =
	x, y, z = 100, 200, 300

	// Printing the types and values
	fmt.Printf("%T, %v\n", x, x)
	fmt.Printf("%T, %v\n", y, y)
	fmt.Printf("%T, %v\n", z, z)
}

Output:

int, 10
int, 20
int, 30
int, 100
int, 200
int, 300

Golang FAQ »




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.