Go · Stage 1 – Storing Information · Lesson 9 of 64

var and :=

Learn Go’s two common variable declaration forms and where each one can be used.

Go offers a full var declaration and a shorter := declaration. Both create variables, but they fit different locations and needs.

Go code

var score = 10
fmt.Println(score)
Line-by-line explanation
  1. var creates score.
  2. No type is written, so Go infers int from 10.
  3. Println displays the value.
Expected output
10

The variable is still statically typed as an integer.

Go code

score := 10
fmt.Println(score)
Line-by-line explanation
  1. score is the new name.
  2. := declares and assigns it.
  3. Go infers the integer type.
  4. Println displays 10.
Expected output
10

The result matches the var form.

Use := for clear local values inside a function. Use var when declaring outside a function, when you need an explicit type, or when the zero value is useful.