Home >Backend Development >Golang >What's the Difference Between `=` and `:=` Assignment Operators in Go?
Understanding := and = Operators in Go
In Go programming, the assignment operators "=" and ":=" may appear interchangeable for assigning values to variables. However, these operators have distinct roles and usage scenarios.
= Operator: Assignment
The "=" operator is used exclusively for assignment. It assigns a value to an existing variable:
var a int a = 10 // Assign the value 10 to the variable 'a'
:= Operator: Declaration and Assignment
In contrast, the ":=" operator combines declaration and assignment. This means it can both create and initialize a new variable at the same time:
b := 10 // Declare and assign the variable 'b' with the value 10
Usage Cases
When to Use =:
When to Use :=:
Example:
Consider the following code:
var c int = 20 d := 30 fmt.Println(c) // Output: 20 fmt.Println(d) // Output: 30
Here, "=" is used to assign the value 20 to the variable "c," which has already been declared. On the other hand, ":=" is used to both declare and initialize the variable "d" with the value 30.
The above is the detailed content of What's the Difference Between `=` and `:=` Assignment Operators in Go?. For more information, please follow other related articles on the PHP Chinese website!