如何为切片创建通用的接收函数?

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

How to create generic receiver function for slice

问题

type slice []T

func (s *slice) remove(element T) []T {

	newSlice := []T{}

	for _, i := range *s {
		if i != element {
			newSlice = append(newSlice, i)
		}
	}
	return newSlice
}

我正在尝试创建一个通用的接收器函数来从切片中删除元素,上面是我正在使用的代码,但是我遇到了"未声明的名称:T"错误。

英文:
type slice []T

func (s *slice) remove(element T) []T {

	newSlice := []T{}

	for _, i:= range s {
		if i != element {
			newSlice = append(newSlice, i)
		}
	}
	return newSlice
}

I am trying to create a generic receiver func to remove elements from a slice, above the code I am working with, but I am getting Undeclared Name: T error..

答案1

得分: 1

这是因为你没有将类型slice定义为泛型类型。你只是将它定义为类型T的切片,而类型T并不存在。

如果你将slice定义为泛型类型,那么你的方法就可以工作:

type slice[T comparable] []T

func (s *slice[T]) remove(element T) []T {

    newSlice := []T{}

    for _, i := range *s {
        if i != element {
            newSlice = append(newSlice, i)
        }
    }
    return newSlice
}

(还需要将range s更改为range *s

英文:

That's because you haven't defined type slice as a generic type. You have just defined it as a slice of type T where type T doesn't exist.

If you do define slice as a generic type, then your approach works:

type slice[T comparable] []T

func (s *slice[T]) remove(element T) []T {

	newSlice := []T{}

	for _, i := range *s {
		if i != element {
			newSlice = append(newSlice, i)
		}
	}
	return newSlice
}

(Also needed to change range s to range *s)

huangapple
  • 本文由 发表于 2022年9月28日 10:12:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/73875499.html
匿名

发表评论

匿名网友

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

确定