Go - Variable





var name type = expression 

// Expression can be a function (os.Open returns a file and an error)
var f, err = os.Open( name)

// var is used to specify explicitly the type (erase the default type)
i := 100 // an int 
var boiling float64 = 100 // a float64

Either the type or the = expression part may be omitted, but not both.


  • the type is omitted, it is determined by the initializer expression.
  • the expression is omitted, the initial value is the zero value for the type

Initialization Time

  • Package-level variables are initialized before main begins
  • Local variables are initialized as their declarations are encountered during function execution.


A variable can be initialized as part of its declaration. If it is not explicitly initialized, it is implicitly initialized to the zero value for its type which is:

The zero value of an aggregate type like an array or a struct has the zero value of all of its elements or fields.

The zero-value mechanism ensures that a variable always holds a well-defined value of its type; This simplifies code and often ensures sensible behavior of boundary conditions without extra work. For example, the below code prints an empty string, rather than causing some kind of error or unpredictable behavior.

var s string 
fmt.Println( s) // ""


  • Tuple assignment
i, j = j, i // swap values of i and j

Blank identifier (Special variable)

The blank identifier (_ ie an underscore) may be used whenever syntax requires a variable name but program logic does not.

Scope, naming and Lifetime

See Go - Name

Documentation / Reference

Powered by ComboStrap