Skip to main content

Variables

There are two ways to declare a variable:

  1. With the var keyword:
var variablename type = value

You always have to specify either type or value (or both).

var age int = 25      // type and value
var name string // type only → defaults to ""
var score = 100 // value only → type inferred as int
  1. With the := sign
variablename := value

In this case, the type of the variable is inferred from the value (means that the compiler decides the type of the variable, based on the value).

It is not possible to declare a variable using :=, without assigning a value to it.

Default (Zero) Values

If you declare a variable with var but don’t give a value, Go sets:

  • Numbers → 0
  • Strings → "" (empty string)
  • Booleans → false
  • Pointers, slices, maps, etc. → nil