如何创建一个具有接口类型输入参数和返回值的函数?

huangapple go评论88阅读模式
英文:

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 &gt; maxSize || page &lt; 1 || pageSize &lt; 1 {
		start = 0
		end = 0
	} else if end &gt; 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

使用type parameters

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
}

huangapple
  • 本文由 发表于 2023年2月12日 22:55:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75427878.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定