Difference between := and = operators in Go

The main difference between := and = operators in Go is that the “:= operator is for short variable declaration + assignment, whereas the = operator is for assignment only. For example, var x int = 10 is the same as x := 10.”

The := operator is used for short variable declaration and initialization within a function body, whereas the = operator assigns a value to an existing, pre-declared variable.

:= (short variable declaration)

The := operator is used for short variable declaration and initialization. It declares a new variable, infers its type based on the assigned value, and initializes it with the given value. This operator can only be used within a function body.

Example

package main

import (
  "fmt"
)

func main() {
  message := "Hello, Gopher!"
  fmt.Println(message)
}

Output

Hello, Gopher!

In this example, the := operator is used to declare and initialize the message variable with “Hello, Gopher!”. The message type is inferred as a string based on the assigned value.

= (assignment)

The = operator is used to assign a value to an existing variable. It does not declare a new variable, which must be defined before using this operator. The variable type should also match the type of the value being assigned.

Example

package main

import (
  "fmt"
)

func main() {
  var message string
  message = "Hello, Gopher!"
  fmt.Println(message)
}

Output

Hello, Gopher!

In this example, the = operator assigns “Hello, Gopher!” to the existing message variable. The variable message was declared with the var keyword, and its type was specified as a string.

That’s it.

Leave a Comment