Home >Backend Development >Golang >How to have a function of an interface that has interface input parameters and a return value of the same type?

How to have a function of an interface that has interface input parameters and a return value of the same type?

王林
王林forward
2024-02-05 23:48:07611browse

How to have a function of an interface that has interface input parameters and a return value of the same type?

Question content

I am trying to implement a function in my utility package that will paginate any type of slice given. It should accept a portion of the interface plus page and page size, and must return the same type of interface.

However, when I try to use the function, I get the error: My input is the same as Interface{}Input

cannot use result (variable of type []entity.something) as []interface{} value in argument to utility.paginateslice compilerincompatibleassign

This 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]
}

Here is an example of me trying to use it which resulted in 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)
}

Correct answer


Use type parameters:

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

The above is the detailed content of How to have a function of an interface that has interface input parameters and a return value of the same type?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete