Sobes.tech
Junior — Middle

What is the difference between using long syntax and short syntax in Go?.

sobes.tech AI

Answer from AI

In Go, there are two ways to assign variables:

  • Long syntax: var x int = 10 or x = 10 (if the variable is already declared).
  • Short syntax: x := 10 — declares and initializes the variable at the same time.

Differences:

  • The short syntax can only be used inside functions and declares new variables.
  • The long syntax is suitable for declaring variables at the package level or when you need to specify the type explicitly.

Example:

func main() {
    var a int = 5  // long syntax
    b := 10        // short syntax
    a = 7          // assignment to an already declared variable
    fmt.Println(a, b)
}

The short syntax is convenient and reduces code, but it is not suitable for all cases.

What is the difference between using long syntax and… - sobes.tech