Compare time.Time with Equal

ID

go.time_equal_operator

Severity

low

Remediation Complexity

simple

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Go

Tags

correctness, reliability

Description

Reports two time.Time values compared with == or !=. The time package provides t1.Equal(t2) to compare the instants correctly.

Rationale

A time.Time carries a monotonic clock reading and a wall-clock location in addition to the instant it represents. Two values that denote the same moment can therefore compare unequal with == (and unrelated values can compare equal), because the operator compares the whole struct. Equal compares the time instants, ignoring the location and monotonic-clock differences.

func compare(a time.Time, b time.Time) {
    if a == b { // FLAW — use a.Equal(b)
    }
}

Remediation

Replace t1 == t2 with t1.Equal(t2) and t1 != t2 with !t1.Equal(t2).