Using structs in Go

Check if a struct is not empty

Supposing we have a Person struct:

type Person struct {
    Name string
    Age uint8
}

Create a Bob var of type Person and populate it with values:

Bob := Person{Name: "Bob", Age: 30}

Check if Bob is an empty struct:

if Bob == (Person{}) {
    fmt.Println("Bob is an empty struct")
} else {
    fmt.Println("Bob is not an empty struct")
}

Compare two structs excluding some fields

Structs can be compared in a straightforward way:

type Person struct {
    Name string
    Age uint8
}

func main() {
    Bob := Person{Name: "Bob", Age: 30}
    OtherBob := Person{Name: "Bob", Age: 30}

    if Bob == OtherBob {
        fmt.PrintLn("Bob is equal to OtherBob")
    } else {
        fmt.Printf("Bob is not equal to OtherBob, Bob: %v, OtherBob: %v\n", Bob, OtherBob)
    }
}

In the example above, the output will be: Bob is equal to OtherBob, as the corresponding fields have the same values for Bob and OtherBob.

In the next example, we will add an ID field to the Person. This field will hold unique identifiers.

type Person struct {
    ID string
    Name string
    Age uint8
}

In this case, straightforward comparison will not work, as ID field has unique values.

Bob := Person{ID: "p1", Name: "Bob", Age: 30}
OtherBob := Person{ID: "p2", Name: "Bob", Age: 30}

if Bob == OtherBob {
    fmt.PrintLn("Bob is equal to OtherBob")
} else {
    fmt.Printf("Bob is not equal to OtherBob, Bob: %v, OtherBob: %v\n", Bob, OtherBob)
}

The output will be: Bob is not equal to OtherBob, Bob: {p1 Bob 30}, OtherBob: {p2 Bob 30}.

In order to exclude ID filed from the comparison, we will introduce an Equal function for type Person and use it in comparison. The Equal function takes other Person as an argument and returns a boolean. Inside, it compares only Name and Age field values, not taking into account the ID field values.

type Person struct {
    ID string
    Name string
    Age uint8
}

func (p Person) Equal(other Person) bool {
    return p.Name == other.Name && p.Age == other.Age
}

func main() {
    Bob := Person{ID: "p1", Name: "Bob", Age: 30}
    OtherBob := Person{ID: "p2", Name: "Bob", Age: 30}

    if Bob.Equal(OtherBob) {
        fmt.PrintLn("Bob is equal to OtherBob")
    } else {
        fmt.Printf("Bob is not equal to OtherBob, Bob: %q, OtherBob: %q\n", Bob, OtherBob)
    }
}

The output will be: Bob is equal to OtherBob.