Golang: How to determine structure whether it is empty

Preface

Using any programming language will encounter the problem of nullification, so how does Golang determine the nullability of a custom structure type?

In fact, the empty structure is not a simple comparison with nil. Please look at the following two methods:

package main

import (
	"fmt"
	"reflect"
)

type A struct {
	name string
	age  int
}

func (a A) IsEmpty() bool {
	return reflect.DeepEqual(a, A{})
}

func main() {
	var a A

	if a == (A{}) { // Brackets cannot be removed
		fmt.Println("a == A{} empty")
	}

	if a.IsEmpty() {
		fmt.Println("reflect deep is empty")
	}
}

Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *