In Go, there is no direct way to check if a struct is “empty” since the concept of an empty struct depends on the context and how you define it. However, you can check if all the fields in a struct have their zero values, which may be considered an empty struct in some cases.
Here’s an example of how you can check if all fields of a struct have their zero values using the reflect package:
package main
import (
"fmt"
"reflect"
)
type Student struct {
Name string
Rollno int
Address string
}
func isEmptyStruct(v interface{}) bool {
val := reflect.ValueOf(v)
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
if !field.IsZero() {
return false
}
}
return true
}
func main() {
s1 := Student{}
s2 := Student{Name: "John Wick", Rollno: 4, Address: "123 Main St"}
fmt.Printf("s1 is empty: %v\n", isEmptyStruct(s1))
fmt.Printf("s2 is empty: %v\n", isEmptyStruct(s2))
}
Output
s1 is empty: true
s2 is empty: false
In this example, we defined a Student struct and create two instances, s1, and s2.
We created a function isEmptyStruct() that takes an interface value as an argument and uses reflection to iterate through the fields of the struct.
If any field has a non-zero value, the function returns false. If all fields have zero values, the function returns true.
We then used the isEmptyStruct() function to check if the Person instances p1 and p2 are empty (have all fields with zero values) and print the results.
Remember to import the reflect package to use reflection functions and methods.
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.