Home >Backend Development >Golang >Go's `:=` vs `=`: When to Use Which Assignment Operator?
As a novice in Go programming, you might have noticed an intriguing duality between := and =. While := was assumed to be the Go equivalent of Python's =, using = in Go also seems to function.
Understanding Assignment Operator (=)
The = operator in Go serves as an assignment operator, assigning values to variables. Its general syntax is:
variable = expression
For instance:
var x = 10 y := 20
In the above example, x is assigned the value 10, and y is assigned the value 20.
Exploring Variable Declarations with :=
:= serves as a short variable declaration, which takes the following form:
name := expression
The type of name is automatically inferred based on the expression. For instance:
a := 10 // a is of type int b := 3.14 // b is of type float64
Key Distinction: Declaration vs Assignment
The crucial difference between := and = lies in their roles. := is a declaration, introducing a new variable, while = is an assignment, assigning a value to an existing variable. This means that := must always declare at least one new variable.
Usage Scenarios
:= can be used in the following scenarios:
Exceptions
Additional Resources
The above is the detailed content of Go's `:=` vs `=`: When to Use Which Assignment Operator?. For more information, please follow other related articles on the PHP Chinese website!