What is the difference between `var` and `:=` in Go?

Beginner

Answer

  • var can be used at package and function level, supports explicit type declaration, and initializes with zero values if not assigned
  • := (short variable declaration) can only be used inside functions, always requires initialization, and uses type inference
// Package level - must use var
var globalVar string

func main() {
    // Both are valid inside functions
    var localVar string    // Zero value: ""
    shortVar := "hello"    // Type inferred as string
}