Home > Software design >  How to find min/max item of a generic slice in golang
How to find min/max item of a generic slice in golang

Time:09-02

I have this golang function to find max item of a slice.

In case the given slice has length of 0, I can't figure out what to return.

Could anybody help me with this ?

Thank you!

func GenericMax[T comparable](a ...T) T {
    vl := reflect.ValueOf(a)

    if len(a) == 0 {
        // How to return ???
    }
}

CodePudding user response:

If you declare a variable of type T and don't assign to it, it will get the default value for its type. That is presumably what you want to return when the slice has a length of zero.

if len(a) == 0 {
    var dflt T
    return dflt
}

another option is to add a default value to the arguments list of the function, and return that default value when you have no value to return.

CodePudding user response:

You can make your function return (T, error). In case the length of the slice is 0, you can return an error alone with the default value for the type errors.New("Slice length cannot be 0").

So your function will look like

func GenericMax[T comparaable](a ...T) (T, error) {
    vl := reflect.ValueOf(a)
    var defaultValue T
    if len(a) == 0 {
        return defaultValue, errors.New("Slice length cannot be 0")
    }
    // Find the max and return it
}
  • Related