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

王林
Release: 2024-02-05 23:48:07
forward
590 people have browsed it

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
Copy after login

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]
}
Copy after login

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)
}
Copy after login


Correct answer


Use type parameters:

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

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template