How to check for an empty struct in Go

This article details a few approaches for checking if a struct is empty in Go. It accounts for structs with comparable and non-comparable fields. Note that an empty struct in Go is one whose fields are all initiaised to their respective zero values.

Comparing with a zero value composite literal

Checking for an empty struct in Go is straightforward in most cases. All you need to do is compare the struct to its zero value composite literal. This method works for structs where all fields are comparable.

main.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{}) // true
	fmt.Println(p2 == Person{}) // false
}

In an if statement, you need to use a parenthesis around the zero value composite literal due to a parsing ambiguity.

if p1 == (Person{}) {

}

When using pointers, make sure you dereference the variable before comparing:

p3 := &Person{}

if *p3 == (Person{}) {

}

Using the reflect package

For a struct that has a non-comparable field (such as a slice, map, or function), the previous approach will not work but you can use the reflect.DeepEqual() method instead as shown below:

main.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{})) // true
	fmt.Println(reflect.DeepEqual(p2, Person{})) // false
}

The DeepEqual() method works if you’re comparing any two structs to find out if they’re equal so it’s not limited to checking for an empty struct.

Another way to specifically check if a struct is empty is by using the Value.IsZero() method that was introduced in Go 1.13:

main.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()) // true
	fmt.Println(reflect.ValueOf(p2).IsZero()) // false
}

Conclusion

I hope this article has helped you figure out how empty structs can be detected in Go. If you have further suggestions or techniques, please mention them in the comments section below.

Thanks for reading, and happy coding!