mdawar.dev

A blog about programming, Web development, Open Source, Linux and DevOps.

Go - Short Variable Declaration

Go provides a shorthand syntax for declaring and initializing variables using the := operator:

  • The short assignment statement := can be used instead of a var declaration
  • Short variable declarations may appear only inside functions
  • They can be used to declare local temporary variables
  • Constants cannot be declared using this syntax
go
func main() {
  // Declare and initialize variables inside a function.
  name := "John"
  age := 20

  // Multiple variables may be declared and initialized in the same declaration.
  i, j := 0, 1
}

Short variable declarations may appear in some contexts such as the initializers for if, for or switch statements:

go
func main() {
  for i := 0; i < 10; i++ {
    // ...
  }

  if err := f(); err != nil {
    // ...
  }

  switch x := f(); x {
    // ...
  }
}

A short variable declaration may act like an assignment only to variables that were already declared in the same block with the same type:

go
func main() {
  f1, err := os.Open("file1")

  f2, err := os.Open("file2") // reassign to "err"
}

A short variable declaration must declare at least 1 new variable:

go
func main() {
  // This code will not compile.
  f, err := os.Open("file1")

  f, err := os.Open("file2") // error: no new variables on left side of :=
}