Home >Backend Development >Golang >Go Assignment Operators: = vs. := — When to Use Which?
Assignment Operators in Go: = vs. :=
In Go programming, the = and := operators are used for assignment. However, they differ in their capabilities and use cases.
= Operator
The = operator assigns a value to an existing variable. It does not declare a new variable but instead updates the value of an existing one. For example:
var foo int = 10 foo = 20
In this example, the variable foo is first declared with the value 10, and then its value is updated to 20 using the = operator.
:= Operator
The := operator is a shorthand for declaring a new variable and assigning it a value in a single statement. It is widely used for assigning values to variables within functions or for creating local variables within a block. For example:
func main() { bar := 20 }
In this example, the variable bar is declared and assigned the value 20 using the := operator. This is equivalent to the following code:
func main() { var bar int bar = 20 }
Use Cases
In summary, the = operator performs simple assignment, while the := operator combines declaration and assignment into a single statement. Understanding the distinction between these operators is crucial for effective Go programming.
The above is the detailed content of Go Assignment Operators: = vs. := — When to Use Which?. For more information, please follow other related articles on the PHP Chinese website!