-
Notifications
You must be signed in to change notification settings - Fork 18.8k
Closed as duplicate of#62642
Labels
LibraryProposalIssues describing a requested change to the Go standard library or x/ libraries, but not to a toolIssues describing a requested change to the Go standard library or x/ libraries, but not to a toolProposal
Milestone
Description
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
-
I thought about using
cmp.Comparebutcmp.Orderedthis does not covertime.Time. At least as far astime.Comparegoes this would be a great alternative. Acmp.Equalmight complement that. -
Another potential pattern might be to introduce general
EqualandCompareinterfaces 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
Labels
LibraryProposalIssues describing a requested change to the Go standard library or x/ libraries, but not to a toolIssues describing a requested change to the Go standard library or x/ libraries, but not to a toolProposal