0
0
Goprogramming~5 mins

Zero values in Go

Choose your learning style9 modes available
Introduction
Zero values give a default starting value to variables when you don't set one. This helps avoid errors from using empty or uninitialized data.
When you declare a variable but don't assign a value right away.
When you want to know what a variable holds before you set it.
When you want to reset a variable to its default state.
When you rely on Go's automatic initialization to keep code simple.
Syntax
Go
var variableName Type
// variableName now holds the zero value for Type
Every type in Go has a zero value, like 0 for numbers, false for booleans, and "" (empty string) for strings.
You don't have to set a value; Go does it automatically when you declare a variable.
Examples
Declares three variables. number is 0, flag is false, and text is an empty string by default.
Go
var number int
var flag bool
var text string
Pointer, slice, and map variables start as nil, which means they point to nothing yet.
Go
var pointer *int
var slice []int
var mapData map[string]int
ch is zero value 0 (no character), f is 0.0 by default.
Go
var ch rune
var f float64
Sample Program
This program shows the zero values of different variable types in Go. It prints each variable's default value.
Go
package main
import "fmt"

func main() {
    var a int
    var b bool
    var c string
    var d *int

    fmt.Println("a (int):", a)
    fmt.Println("b (bool):", b)
    fmt.Println("c (string):", c)
    fmt.Println("d (*int):", d)
}
OutputSuccess
Important Notes
Zero values help prevent bugs by ensuring variables always have a known starting value.
For complex types like slices or maps, zero value means nil, so you must initialize them before use.
You can check if a variable is zero by comparing it to its zero value.
Summary
Zero values are default values Go gives variables when you don't set them.
Each type has its own zero value, like 0, false, "", or nil.
Using zero values helps keep your code safe and predictable.