2

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?

aronchick
  • 6,786
  • 9
  • 48
  • 75

1 Answers1

3

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.

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118