英文:
How can I have a function with interface input parameter and interface of same type return value?
问题
我正在尝试在我的实用程序包中实现一个函数,用于对给定的任何类型的切片进行分页。它应该接受一个接口切片,以及页码和每页大小,并且必须返回相同类型的接口。
然而,当我尝试使用该函数时,我得到了一个错误,说我的输入与interface{}
类型的输入不匹配。
无法将结果(类型为
[]entity.Something
的变量)作为[]interface{}
类型的值传递给utility.PaginateSlice的参数,编译器不兼容的赋值
这是我的函数:
// PaginateSlice,根据页码和每页大小对切片进行分页。
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]
}
这是我尝试使用它导致失败的示例:
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)
}
英文:
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)
}
答案1
得分: 4
func PaginateSlice[S ~[]T, T any](x S, page, pageSize int) S {
// 在这里插入问题中函数的主体
}
英文:
Use type parameters:
func PaginateSlice[S ~[]T, T any](x S, page, pageSize int) S {
// insert body of function from question here
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论