0
0
GoConceptBeginner · 3 min read

What is Zero Value in Go: Explanation and Examples

In Go, the zero value is the default value assigned to a variable when it is declared but not explicitly initialized. Each type has its own zero value, like 0 for numbers, "" for strings, and nil for pointers or slices.
⚙️

How It Works

Think of zero value as the starting point or the "empty" state for any variable in Go. When you create a variable but don’t give it a value, Go automatically fills it with a default value that makes sense for its type. This helps avoid errors from using uninitialized variables.

For example, if you declare a number, its zero value is 0. For text, it’s an empty string "". For more complex types like pointers or slices, the zero value is nil, which means "no value" or "nothing". This automatic assignment is like getting a clean slate to start with.

💻

Example

This example shows variables declared without values and their zero values printed.

go
package main

import "fmt"

func main() {
    var number int
    var text string
    var flag bool
    var ptr *int

    fmt.Println("Zero value of int:", number)
    fmt.Println("Zero value of string:", text)
    fmt.Println("Zero value of bool:", flag)
    fmt.Println("Zero value of pointer:", ptr)
}
Output
Zero value of int: 0 Zero value of string: Zero value of bool: false Zero value of pointer: <nil>
🎯

When to Use

Zero values are useful when you want to declare variables without immediately assigning values. This is common in situations like preparing variables for later use or when reading data that might not be available yet.

For example, when creating structs or working with slices, zero values let you safely declare variables without worrying about uninitialized data causing bugs. It also helps in functions where you want to return a default value if no input is given.

Key Points

  • Zero value is the default value for any variable type in Go.
  • It prevents errors from uninitialized variables.
  • Each type has a specific zero value, like 0, "", false, or nil.
  • Zero values help write safer and cleaner code.

Key Takeaways

Zero value is Go's default for uninitialized variables.
Each data type has its own zero value, like 0 for int and "" for string.
Using zero values prevents bugs from uninitialized variables.
Zero values allow safe variable declarations before assignment.