Skip to the workspace
Pebellslearn by building
Variables & Constants  ›  Lesson

var vs :=

var vs := 12 minvar declares a variable anywhere and can give it just a type, while := declares and initialises in one step, works only inside functions and must introduce at least one new name.

golang / var vs :=

Explore each scene at your own pace.

01 · The rule

The rule

var vs :=

var declares a variable anywhere and can give it just a type, while := declares and initialises in one step, works only inside functions and must introduce at least one new name.

Choose an explicit declaration or short declaration and diagnose accidental shadowing.

tally needs somewhere to keep things: the file name, the list of words, a running total. Go gives you two ways to declare a variable, and knowing which one fits saves you a surprising number of compile errors.

The rule

var works everywhere and allows a bare type; := is function-only and needs a new name.

var is the full form. You can give a type, a value, or both:

var minLength = 3        // type inferred: int
var total int            // no value: starts at 0
var path string = "notes.txt"

It works at package level (outside any function) and inside functions. A group of them can share one block:

var (
	minLength = 3
	verbose   = false
)

:=, the short declaration, declares and assigns in one step and infers the type from the value:

func main() {
	path := "notes.txt"
	words, err := readWords(path)
	// ... use words and err
}

Its rules:

  1. It only works inside functions. At package level it is a syntax error.
  2. It must declare at least one new variable on the left. total := 0 twice in the same block fails with "no new variables on left side of :=".
  3. With several names, the new ones are declared and the existing ones are simply assigned. That is why a, err := f() followed by b, err := g() is fine: b is new, err is reused.

Plain = never declares; it only assigns to a variable that already exists.

And one rule for both: a local variable you declare but never use is a compile error.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.