Skip to content

proposal: time: add time.Equal and time.Compare #71810

@andig

Description

@andig

Proposal Details

Observation

I've just found myself writing this code working with timestamps:

if !slices.ContainsFunc(keys, func(ts time.Time) bool {
	return ts.Equal(r.Start)
}) {
	keys = append(keys, r.Start)
}

keys = slices.SortedFunc(slices.Values(keys), func(a, b time.Time) int {
	return a.Compare(b)
})

While this is a perfectly valid way of doing things it felt odd the I couldn't simply do

slices.ContainsFunc(keys, time.Equal)
slices.SortedFunc(slices.Values(keys), time.Compare)

Proposal

Especially the comparison takes careful consideration of order (i.e. how to compare). For simplicity, I propose adding

func Equal(a, b Time) bool {
	return a.Equal(b)
}

func Compare(a, b Time) int {
	return a.Compare(b)
}

While Go strives to have only one way of doing things there are other examples of comfort functions like e.g. UnixMilli, UnixMicro that are not strictly necessary.

Alternatives

  1. I thought about using cmp.Compare but cmp.Ordered this does not cover time.Time. At least as far as time.Compare goes this would be a great alternative. A cmp.Equal might complement that.

  2. Another potential pattern might be to introduce general Equal and Compare interfaces and a matching adapter function:

    interface Equal[T any] {
        Equal(to T) bool
    }
    
    func Equal[T Equal]() func(a, b T) bool {
        return a.Equal(b)
    }
    
    // usage (not sure if the type could be inferred)
    slices.ContainsFunc(keys, Equal[time.Time]())
    
    interface Comparable[T any] {
        Compare(with T) int
    }
    
    func Compare[T Comparable]() func(a, b T) int {
        return a.Compare(b)
    }
    
    // usage (not sure if the type could be inferred)
    slices.SortedFunc(slices.Values(keys), Compare[time.Time]())

Metadata

Metadata

Assignees

No one assigned

    Labels

    LibraryProposalIssues describing a requested change to the Go standard library or x/ libraries, but not to a toolProposal

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions