Default Zero Values in Go

Default Zero Values in Go

Table of contents

In Go (also referred to as Golang), when you declare a variable without explicitly initializing it with a value, it is given a default value. This default value is called the "zero value" for its type. Here's what the zero values are for some common types in Go:

  • int: 0

  • float64: 0.0

  • bool: false

  • string: "" (empty string)

  • pointer: nil

  • slice: nil

  • map: nil

  • channels: nil

  • functions: nil

  • interfaces: nil

  • array: Array of appropriate length filled with zero values for the array's type. For example, the zero value of [3]int is [0, 0, 0].

Here's a simple example:

package main

import "fmt"

func main() {
    var i int
    var f float64
    var b bool
    var s string
    fmt.Printf("%v %v %v %q\n", i, f, b, s)
}

When run, this program will print:

0 0 false ""

Exercises:

  1. Basic Zero Values:

    • Declare a variable of type *int and print its value.

    • Declare a variable of type []string and print its value.

    • Declare a variable of type map[string]int and print its value.

  2. Struct Zero Values:

    • Define a struct Person with Name as a string and Age as an int.

    • Declare a variable of type Person and print its value.

  3. Zero Value Functionality:

    • Declare a slice of ints.

    • Without initializing the slice, try to append a value to it and print the result.

Solutions:

  1. Basic Zero Values:
package main

import "fmt"

func main() {
    var ptr *int
    var slice []string
    var m map[string]int
    fmt.Println(ptr, slice, m)
}

Output:

<nil> [] <nil>
  1. Struct Zero Values:
package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

func main() {
    var p Person
    fmt.Println(p)
}

Output:

{ 0}
  1. Zero Value Functionality:
package main

import "fmt"

func main() {
    var numbers []int
    numbers = append(numbers, 5)
    fmt.Println(numbers)
}

Output:

[5]

This demonstrates that even though the zero value of a slice is nil, you can still use append() with it.