How to get the zero value in Go

May 15, 2022 1 min read

Getting the zero value in Go is useful especially when validating if some data is empty.

Previously this could only be done with the reflect package but with the introduction of generics in Go 1.18 this can be done with a simple function which takes a type argument and creates a zero value of that type.

package main

import "fmt"

func zero[T any]() T {
    var zero T
    return zero

func main() {
    fmt.Println(zero[int]())                    // 0
    fmt.Println(zero[[]string]())               // []
    fmt.Println(zero[struct{ name float64 }]()) // {0}

Subscribe to not miss out on new content.

Keep up with things amazing things happening in technology, business, software, and the web.

You will never receive spam and you can unsubscribe at any time.
Mykolas Krupauskas

Written by Mykolas Krupauskas. A passionate software developer from Lithuania, currently situated in the Netherlands. Helping people create value with technology.