CodeBlanks Logo Icon CodeBlanks

Zero value

Learn that every type in Go has a zero value.

Zero value

In Go every type has a zero value. When a variable is declared without an explicit value, it gets this zero value. This prevents 'undefined behaviour' issues.

For numeric types the zero value is 0, for bool false, for string "" (empty), for pointer and interface nil.

This behaviour makes Go safe; no variable starts with 'garbage'. When a new struct is created, all its fields take their zero values.

Zero value table

Zero values of common types:

  • int, float64: 0
  • bool: false
  • string: ""
  • pointer, slice, map, interface: nil
  • struct: each field's zero value

This table is often consulted in daily coding. Knowing zero values matters especially when checking struct fields.

Practice Zero values

Declare var n int, var f float64, var s string and var b bool without values. Print them with fmt.Printf("%d %g %q %t\n", n, f, s, b).

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

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

Expected output

0 0 "" false

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the zero value of a string variable?

  • nil
  • 0
  • empty string ("")
  • false Correct answer

Explanation: The zero value of string is the empty string.

2 Bool zero value

Question
The zero value of a bool variable: ____
Answer
The zero value of a bool variable: false

Explanation: The zero value of bool is false.

3 Match the zero values

Term Meaning
int 0
bool false
string empty
pointer nil

All lessons in Beginner