In Go language, = and := are two different assignment operators, used in different scenarios. Understanding their differences is crucial for writing correct and efficient Go code.

Basic Definitions and Usage

= is the standard assignment operator, used to assign values to already declared variables. Whereas := is the short variable declaration operator, which both declares and initializes a new variable. The following example shows their typical usage.

package main

import "fmt"

func main() {
    // Use := to declare and initialize a variable
    x := 10
    fmt.Println(x) // Output: 10
    
    // Use = to assign a value to an already declared variable
    x = 20
    fmt.Println(x) // Output: 20
}

Note: := can only be used inside functions, not for declaring package-level variables.

Scope and Variable Declaration

The := operator automatically infers the variable type and restricts its scope to the current code block (e.g., inside a function). In contrast, = is only used for assignment, requiring the variable to have been declared via var or :=. The following code demonstrates the difference in scope.

package main

import "fmt"

var globalVar int = 5 // Package-level variable, must be declared using var

func exampleFunction() {
    // Use := to declare a local variable inside the function
    localVar := 15
    fmt.Println(localVar) // Output: 15
    
    // Use = to modify the package-level variable
    globalVar = 25
    fmt.Println(globalVar) // Output: 25
}

func main() {
    exampleFunction()
    // fmt.Println(localVar) // Error: localVar is undefined, as its scope is limited to exampleFunction
}

Type Inference and Multiple Assignment

:= supports type inference and multiple assignment, making the code more concise. For example, you can declare multiple variables simultaneously.

package main

import "fmt"

func main() {
    // Use := for multiple assignment
    a, b := 1, "hello"
    fmt.Println(a, b) // Output: 1 hello
    
    // Use = for multiple assignment (variables must already be declared)
    var c int
    var d string
    c, d = 2, "world"
    fmt.Println(c, d) // Output: 2 world
}

Warning: When using := , at least one variable on the left side must be newly declared, otherwise a compilation error will occur. For example, after x := 5, doing x := 10 again is incorrect.

Performance and Best Practices

In terms of performance, there is no significant difference between = and :=, but using them correctly can improve code readability and maintainability. It is generally recommended to prioritize using := for declaring local variables inside functions, and use var and = when explicit types or package-level declarations are needed.