Why does using time.Time.Compare like this work?

159 views
Skip to first unread message

cpu...@gmail.com

unread,
Feb 20, 2025, 12:57:35 PMFeb 20
to golang-nuts
Sorry for not finding a better than this click bait subject. 

In https://github.com/golang/go/issues/62642 this suggestion was made:

slices.SortFunc(times, time.Time.Compare)

It's totally unclear to me how Time.Compare matches the compare func(a,b T) int signature? I assume it's something from the golang spec, but which part?

Are there other typical uses of this capability that are common?

Cheers,
Andi

Mike Schilling

unread,
Feb 20, 2025, 1:30:22 PMFeb 20
to golang-nuts
Any method can be called as a normal function with the receiver as the first argument. Thus you can call time.Time.Compare(time1, time2) .

Dan Kortschak

unread,
Feb 20, 2025, 1:34:36 PMFeb 20
to golan...@googlegroups.com
On Thu, 2025-02-20 at 09:57 -0800, cpu...@gmail.com wrote:
> Sorry for not finding a better than this click bait subject. 
>
> In https://github.com/golang/go/issues/62642 this suggestion was
> made:
>
> slices.SortFunc(times, time.Time.Compare)
>
> It's totally unclear to me how Time.Compare matches the compare
> func(a,b T) int signature? I assume it's something from the golang
> spec, but which part?

In https://go.dev/ref/spec#Method_expressions

Function values derived from methods are called with function call
syntax; the receiver is provided as the first argument to the call.
That is, given f := T.Mv, f is invoked as f(t, 7) not t.f(7).


So https://pkg.go.dev/time#Time.Compare, func (t Time) Compare(u Time)
int, becomes time.Time.Compare(t, u Time) int.

Mike Schilling

unread,
Feb 20, 2025, 1:36:00 PMFeb 20
to golang-nuts
See "Method expressions" in the Go Programming Language Specification.

Diogo Lisboa

unread,
Feb 20, 2025, 2:07:42 PMFeb 20
to golang-nuts
You have to remember that methods are just regular functions with the receiver as the first parameter. From the spec (https://go.dev/ref/spec#Method_declarations):

> A method is a function with a receiver.

This mean that if you detach the method from the receiver, which time.Time.Compare does, then it requires two arguments instead of one.

a := time.Now()
b := a.Add(1 * time.Hour)
cmp := time.Time.Compare
cmp(a) // error: not enough arguments in call to cmp
cmp(a, b) // ok




Diogo Lisboa

cpu...@gmail.com

unread,
Feb 20, 2025, 2:41:20 PMFeb 20
to golang-nuts
All great answers and thank you for the spec link!
Reply all
Reply to author
Forward
0 new messages