Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an interface/type in golang for implementing > with generics? [duplicate]

Tags:

go

I'm trying to find a comparable-like interface that I can use in the following code:

func SliceMax[T comparable](ts []T) (T, error) {
    if len(ts) == 0 {
        return 0, errors.New("cannot get max from empty slice")
    }

    m := ts[0]
    for _, e := range ts {
        if e > m {
            m = e
        }
    }
    return m, nil
}

But comparable doesn't work (it fails on the > sign). Is there a built in interface here or do I need to write my own?

like image 451
aronchick Avatar asked Oct 21 '25 20:10

aronchick


1 Answers

The predeclared type comparable is for things that are comparable with == and != and doesn't include greater than or less than. You can use constraints.Ordered from the go exp repository, although you'll also have to change return 0, ... to something like var zero T; return zero, ... because for example strings are comparable but don't have 0.

It's not directly relevant to your question, but as a small code-review comment, a value of type []T is a slice, not an array (an array has a fixed size), so I'd probably call the function SliceMax and I'd try to avoid including the type (ie: slice or array) in the name of the argument that's currently named typeArray (it's not an array of type -- it's neither an array nor are its elements a type), and pick something generic like ts although I know that's not to everyone's taste.

like image 107
Paul Hankin Avatar answered Oct 24 '25 14:10

Paul Hankin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!