Golang Variables Declaration, Assignment and Scope Tutorial

Golang Variables

This tutorial will explain how to work with variables in Golang, and some conventions used for idiomatic Go code.
Variables in Golang, just like in other languages, are used to store and represent data. Every variable in Go has a type and a value.

If you just want to read some example code, you can view it on Github.

Golang Variable Declaration

Lets look at the declaration of an integer type:

var i int = 5

This declares a variable named i of type int with a value of 5. The Go compiler is pretty smart, so you can sometimes omit some declarations. For example:

var i = 5

The compiler infers that 5 is of type int, and so assigns that type to i.

Default Values with Golang Variables

We can also declare the type without declaring the value. If we do this, the variable is assigned a default value, which depends on the type:

var i int

Now the value of i is initialized to the default value, which is 0 for the int type.

Different types have different default values:

typeDefault ValueNotes
int0Initialized to 0
float640.0Initialized to 0
string""Empty string
*intnilPointers to any type default to nil
struct{a int}{a: 0}structs initialize to the default values of their attributes
func()nilFunction variables are initialized as nil

Shorthand Declaration