Search code examples
gointerface

How can I have a function with interface input parameter and interface of same type return value?


I am trying to implement a function in my utility package for pagination of slices with any types of slice given. It is supposed to accept an slice of interfaces plus the page and pagesize and must return an interface of the same type.

However, when I try to use the function I get the error that my input does not match the interface{} input

cannot use result (variable of type []entity.Something) as []interface{} value in argument to utility.PaginateSlice compilerIncompatibleAssign

Here is my function:

// PaginateList, paginates a slice based upon its page and pageSize.
func PaginateSlice(x []interface{}, page, pageSize int) []interface{} {
    var maxSize int = len(x)

    start := (page - 1) * pageSize
    end := start + pageSize - 1

    if start > maxSize || page < 1 || pageSize < 1 {
        start = 0
        end = 0
    } else if end > maxSize {
        end = maxSize
    }

    return x[start:end]
}

and here is an example of me trying to use it leading to failure:

var result []entity.Something

tmps := utility.PaginateSlice(dataOfSomethingType, pagination.Page, pagination.PageSize)
for _, tmp := range tmps {
    if value, ok := tmp.(entity.Something); ok {
    result = append(result, value)
}

Solution

  • Use type parameters:

    func PaginateSlice[S ~[]T, T any](x S, page, pageSize int) S {
        // insert body of function from question here
    }