Self-referential generics?

124 views
Skip to first unread message

Shawn Smith

unread,
Apr 10, 2022, 1:48:21 PM4/10/22
to golang-nuts
// ... imagine some comparison sort algorithm

func cmpSort[C Cmpable](x []C) {
    for i, val := range x {
        if i == 0 {
            continue
        }
        _ = val.Cmp(x[i-1])
    }
}

// Cmpable should include big.Int, big.Float, big.Rat, by virtue of their Cmp methods. So how do i define this better?

type Cmpable interface {
    Cmp(other any) int
}
// TODO: how do i replace "any" with "this type". "Cmpable" doesn't work as that would be any Cmpable, not THIS Cmpable.

Axel Wagner

unread,
Apr 10, 2022, 2:23:47 PM4/10/22
to Shawn Smith, golang-nuts
You can use

type Comparable[T any] interface {
    Cmp(other T) int
}

then *big.Int implements `Comparable[*big.Int]` and you can write

func cmpSort[T Comparable[T]](x []C) { … }

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/4f167deb-bf63-43db-9ec9-c4c451c14d09n%40googlegroups.com.

Shawn Smith

unread,
Apr 10, 2022, 3:11:50 PM4/10/22
to Axel Wagner, golang-nuts
Thanks! This seems obvious now just looking at it, but it was stumping me.

I might add for someone that may see this later, in the future it *might* not be needed to do it this way, if all you really just want {Int | Float | Rat} as future versions are supposed to let us use methods in such constrained types if a method is present in all the types, like Cmp in this case, but I'm not sure if it clear that >1.18 will handle this particular case where it is only the same method signature if you note that the param type is the same as the method receiver type.
Reply all
Reply to author
Forward
0 new messages