Home »
Golang
How to check if structure is empty in Golang?
Checking structure is empty or not: Here, we are going to learn how to check whether a structure is empty or not in Golang?
Submitted by Anshuman Singh, on July 03, 2019 [Last updated : March 05, 2023]
Golang Empty Structure
The size of an empty structure is zero in Golang. Here, empty structure means, there is no field in the structure.
Syntax
Type structure_name struct {
}
There are many ways to check if structure is empty. Examples are given below.
Golang code to check whether a structure in an empty or not
Example 1
package main
import (
"fmt"
)
type Person struct {
}
func main() {
var st Person
if (Person{} == st) {
fmt.Println("It is an empty structure")
} else {
fmt.Println("It is not an empty structure")
}
}
It is an empty structure
Example 2
package main
import (
"fmt"
)
type Person struct {
age int
}
func main() {
var st Person
if (Person{20} == st) {
fmt.Println("It is an empty structure")
} else {
fmt.Println("It is not an empty structure")
}
}
It is not an empty structure
If a structure has fields, then how to check whether structure has been initialised or not?
Please follow given below examples...
Syntax
Type structure_name struct {
variable_name type
}
Example 1
package main
import (
"fmt"
"reflect"
)
type Person struct {
age int
}
func (x Person) IsStructureEmpty() bool {
return reflect.DeepEqual(x, Person{})
}
func main() {
x := Person{}
if x.IsStructureEmpty() {
fmt.Println("Structure is empty")
} else {
fmt.Println("Structure is not empty")
}
}
Output
Structure is empty
Example 2
package main
import (
"fmt"
"reflect"
)
type Person struct {
age int
}
func (x Person) IsStructureEmpty() bool {
return reflect.DeepEqual(x, Person{})
}
func main() {
x := Person{}
x.age = 20
if x.IsStructureEmpty() {
fmt.Println("Structure is empty")
} else {
fmt.Println("Structure is not empty")
}
}
Output
Structure is not empty
Using switch statement
Example 1
package main
import (
"fmt"
)
type Person struct {
}
func main() {
x := Person{}
switch {
case x == Person{}:
fmt.Println("Structure is empty")
default:
fmt.Println("Structure is not empty")
}
}
Output
Structure is empty
Example 2
package main
import (
"fmt"
)
type Person struct {
age int
}
func main() {
x := Person{}
switch {
case x == Person{1}:
fmt.Println("Structure is empty")
default:
fmt.Println("Structure is not empty")
}
}
Output
Structure is not empty