Home >Backend Development >Golang >What's the Difference Between `=` and `:=` Assignment Operators in Go?

What's the Difference Between `=` and `:=` Assignment Operators in Go?

Susan Sarandon
Susan SarandonOriginal
2024-12-20 10:10:14480browse

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 =:

  • Assigning values to existing variables
  • Modifying the value of a declared variable

When to Use :=:

  • Declaring and initializing new variables
  • Assigning values to variables within the same line of code
  • To shorten the declaration and assignment process

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn