英文:
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
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论