How to check empty struct in golang?
May 19, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
Today, we are going to learn how to check an empty struct in golang, here we will use some common syntax to struct is empty or not.
Here, we will take an example empty struct and not an empty struct and we apply conditions on both structs after that we will see the output.
In the following example, I’m going to create an empty struct variable, after that, I will put two if... else
statements, the first one is empty and in the second I will put some data.
let’s write a code.
package main
import (
"fmt"
"time"
)
type Session struct {
playerId string
beehive string
timestamp time.Time
}
func main() {
session := Session{}
if (Session{}) == session {
fmt.Println("empty")
} else {
fmt.Println("Not empty")
}
if (Session{playerId: "1"}) == session {
fmt.Println("empty")
} else {
fmt.Println("Not empty")
}
}
As per expectation, it should print that the first one is empty, and the second one is not empty.
let’s check the output.
All the best 👍