Junior Dev Blog

Variable Semantics in Golang

2022-08-26 at Golang category

This answer is originally posted on Stackoverflow and all the credit goes to it's author, link to the OG post and answer can be found below

:= is for both declaration, assignment, and also for redeclaration; and it guesses (infers) the variable's type automatically.

For example, foo := 32 is a short-hand form of:

var foo int
foo = 32

// OR:
var foo int = 32

// OR:
var foo = 32

/ There are some rules: /

1st Rule

You can't use := outside of funcs. It's because, outside a func, a statement should start with a keyword.

// no keywords below, illegal.
illegal := 42

// `var` keyword makes this statement legal.
var legal = 42

func foo() {
  alsoLegal := 42
  // reason: it's in a func scope.
}

2nd Rule

You can't use them twice (in the same scope):

legal := 42
legal := 42 // <-- error

Because, := introduces "a new variable", hence using it twice does not redeclare a second variable, so it's illegal.

3rd Rule

You can use them for multi-variable declarations and assignments:

foo, bar   := 42, 314
jazz, bazz := 22, 7

4th Rule (Redeclaration)

You can use them twice in "multi-variable" declarations, if one of the variables is new:

foo, bar  := someFunc()
foo, jazz := someFunc()  // <-- jazz is new
baz, foo  := someFunc()  // <-- baz is new

This is legal, because, you're not declaring all the variables, you're just reassigning new values to the existing variables, and declaring new variables at the same time. This is called redeclaration.

5th Rule

You can use the short declaration to declare a variable in a newer scope even if that variable is already declared with the same name before:

var foo int = 34

func some() {
  // because foo here is scoped to some func
  foo := 42  // <-- legal
  foo = 314  // <-- legal
}

Here, foo := 42 is legal, because, it declares foo in some() func's scope. foo = 314 is legal, because, it just assigns a new value to foo.

6th Rule

You can declare the same name in short statement blocks like: if, for, switch:

foo := 42
if foo := someFunc(); foo == 314 {
  // foo is scoped to 314 here
  // ...
}
// foo is still 42 here

Because, foo in if foo := ..., only belongs to that if clause and it's in a different scope.

So, as a general rule: If you want to easily declare a variable you can use :=, or, if you only want to overwrite an existing variable, you can use =.

Original Answer Link https://stackoverflow.com/a/45654233

Zulfiqar Ali

Personal blog by Zulfiqar Ali.

developer tutorial treats