Start learning free

LESSON 612 OF 639 · OBJECT-ORIENTED PROGRAMMING

Comparing Objects in Go in Go

Lesson

TL ; DR:

Go compares structs field by field. Two structs are equal with == when all their fields are equal. A struct can also be a map key, so a map[Time]bool works as a set.


type Time struct {
    hour int
    minute int
}

alarms := map[Time]bool{}
alarms[Time{hour: 9, minute: 30}] = true


Full lesson:

In many languages, two objects with the same values aren't equal by default. They count as two different objects. Go's structs are values, so Go does what you mean.

var a = Time{hour: 9, minute: 30}
var b = Time{hour: 9, minute: 30}
fmt.Println(a == b)    // true

Comparable structs

A struct is comparable when every field is. Numbers, strings and booleans are. Then == and != compare the fields one by one.

A slice or a map field isn't comparable. With one, a == b doesn't compile.

Structs as map keys

Go has no set type. A map with bool values plays that role. Its keys can be any comparable type, so a Time works. Two equal times are one key.

Pointers compare addresses

A pointer such as &Time{hour: 9, minute: 30} is different. Two pointers are equal only when they point to the same struct. Compare and store the struct values instead.


Your task

Time is a struct with an int hour and an int minute. Declare its two fields. Then create alarms, a map from Time to bool.

mainFunction compares three times. Then it adds them to alarms.

Expected output:

a and b are the same time
a and c are different times
alarms: 2
STEP 1 OF 2
    Ctrl + Enter to check

    Comparing Objects in Go

    Keep going with Go500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free