Skip to content

Latest commit

 

History

History
51 lines (33 loc) · 2.23 KB

2.06.md

File metadata and controls

51 lines (33 loc) · 2.23 KB

2.06 Zero Value

To understand the zero value, we also have to understand initialization. In order to do that, let's do a little review about declaring and assigning.

package main

import (
	"fmt"
)

var z int // DELCARE a VARIABLE is of TYPE int

func main() {
	z = 21 // ASSIGN a VALUE to that variable
	fmt.Println(z)	 
}

We declare a variable and its type, then we assign a value of the right type to that variable.

Initialization is the initial time you assign a value to a variable. So, where we have ASSIGN, we could also call that initialize.

Initialization: In computer programming, initialization is the assignment of an initial value for a data object or variable.

It's the first time that you assign a value to a variable. Things in a computer are stored in memory. In the computer you have memory. Memory is like a big post office with post office boxes. Each of those PO boxes has an address, and you can store things in each PO box.

The initial time you store a value in memory, is called initialization.

So, what happens if we declare a variable but do not assign a value to it, then try to print it out.

package main

import (
	"fmt"
)

var z int  // DELCARE a VARIABLE is of TYPE int

func main() {
	fmt.Println(z)
}

0

Every type in Go has a zero value. If you declare a variable to be of a certain type, but we haven't assigned an initial value, then the compiler is going to assign that value for us. For an int it is 0, for float it's 0.0 for a string it's the empty string, for bool it's false, and nil for pointers, functions, interfaces, slices, channels, maps.

The official documentation for zero value says, "When storage is allocated for a variable, either through a declaration or a call of new, or when a new value is created, either through a composite literal or a call of make, and no explicit initialization is provided, the variable or value is given a default value."

When storage (or memory) is allocated, and no explicit initialization is provided... so when you declare a variable, but don't assign a value, it will be assigned a zero value.