snippetgoCritical
How to check for an empty struct?
Viewed 0 times
emptystructhowcheckfor
Problem
I define a struct ...
Sometimes I assign an empty session to it (because nil is not possible)
Then I want to check, if it is empty:
Obviously this is not working. How do I write it?
type Session struct {
playerId string
beehive string
timestamp time.Time
}Sometimes I assign an empty session to it (because nil is not possible)
session = Session{};Then I want to check, if it is empty:
if session == Session{} {
// do stuff...
}Obviously this is not working. How do I write it?
Solution
You can use == to compare with a zero value composite literal because all fields in
playground example
Because of a parsing ambiguity, parentheses are required around the composite literal in the if condition.
The use of
An alternative to comparing the entire value is to compare a field that must be set to a non-zero value in a valid session. For example, if the player id must be != "" in a valid session, use
Session are comparable:if (Session{}) == session {
fmt.Println("is zero value")
}playground example
Because of a parsing ambiguity, parentheses are required around the composite literal in the if condition.
The use of
== above applies to structs where all fields are comparable. If the struct contains a non-comparable field (slice, map or function), then the fields must be compared one by one to their zero values.An alternative to comparing the entire value is to compare a field that must be set to a non-zero value in a valid session. For example, if the player id must be != "" in a valid session, use
if session.playerId == "" {
fmt.Println("is zero value")
}Code Snippets
if (Session{}) == session {
fmt.Println("is zero value")
}if session.playerId == "" {
fmt.Println("is zero value")
}Context
Stack Overflow Q#28447297, score: 340
Revisions (0)
No revisions yet.