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,
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.
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 :
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