How to Check for an Empty Struct in Go

This article outlines a few methods to determine if a struct is empty in Go, applicable to structs with both comparable and non-comparable fields. An empty struct in Go refers to one where all fields are set to their respective zero values.

Checking with zero value composite literal

For structs containing only comparable fields, you only need to compare the struct instance to its zero value composite literal:

go
package main

import (
	"fmt"
)

type Person struct {
	name  string
	age   int
	email int
}

func main() {
	var p1 Person

	p2 := Person{
		name: "John",
		age:  45,
	}

	fmt.Println(p1 == Person{})
	fmt.Println(p2 == Person{})
}
output
true
false

Ensure to use parentheses around the struct literal in if statements to avoid parsing issues:

go
if p1 == (Person{}) {

}

For pointers to structs, ensure to dereference before comparing:

go
p3 := &Person{}

if *p3 == (Person{}) {

}

Using reflect.DeepEqual()

For structs with non-comparable fields (slices, maps, functions), use reflect.DeepEqual():

go
package main

import (
	"fmt"
	"reflect"
)

type Person struct {
	name            string
	age             int
	email           int
	favouriteColors []string // non-comparable field
}

func main() {
	var p1 Person

	p2 := Person{
		name:            "John",
		age:             45,
		favouriteColors: []string{"red", "green"},
	}

	fmt.Println(reflect.DeepEqual(p1, Person{}))
	fmt.Println(reflect.DeepEqual(p2, Person{}))
}
output
true
false

The DeepEqual() method works for any struct comparison, not just for checking emptiness.

Using reflect.Value.IsZero()

Introduced in Go 1.13, the reflect.Value.IsZero() method provides another way to check for empty structs:

go
package main

import (
	"fmt"
	"reflect"
)

type Person struct {
	name            string
	age             int
	email           int
	favouriteColors []string // non-comparable field
}

func main() {
	var p1 Person

	p2 := Person{
		name:            "John",
		age:             45,
		favouriteColors: []string{"red", "green"},
	}

	fmt.Println(reflect.ValueOf(p1).IsZero())
	fmt.Println(reflect.ValueOf(p2).IsZero())
}
output
true
false

Final thoughts

These techniques offer reliable ways to identify empty structs in Go, catering to different field types and struct characteristics. If you have further suggestions, please mention them in the comments section below.

Thanks for reading, and happy coding!