structgo

How to check for an empty struct?


I define a struct ...

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 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")
    }