Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Generics 如何实现通用切片追加器?_Generics_Go_Slice - Fatal编程技术网

Generics 如何实现通用切片追加器?

Generics 如何实现通用切片追加器?,generics,go,slice,Generics,Go,Slice,我是新来的。我正在尝试编写一个通用的appender函数。这是一种简化,但它试图为处理某些列表创建一个干净的界面。具体而言,我对由此产生的两个错误有疑问: package main type GenericFunc func() *interface{} func Append(ints interface{}, f GenericFunc) { ints = append(ints, f()) } func ReturnInt() *int { i := 1 ret

我是新来的。我正在尝试编写一个通用的appender函数。这是一种简化,但它试图为处理某些列表创建一个干净的界面。具体而言,我对由此产生的两个错误有疑问:

package main

type GenericFunc func() *interface{}
func Append(ints interface{}, f GenericFunc) {
    ints = append(ints, f())
}

func ReturnInt() *int {
    i := 1
    return &i
}

func main() {
    var ints []*int
    Append(ints, ReturnInt)
}
prog.go:5:18:要追加的第一个参数必须是slice;有接口 {}prog.go:15:11:无法使用ReturnInt类型func*int作为类型 要追加的参数中的GenericFunc

为什么ReturnInt不能是GenericFunc类型?如果这不起作用,我根本不理解接口{}如何与函数一起使用。。可以吗? 如何接受通用切片并使用反射将其追加?这将涉及检查GenericFunc是否返回与切片相同的类型,但在此之后应该可以进行追加。 GenericFunc的类型func*接口{}type类型和ReturnInt的类型func*int是不同的类型。返回一个*接口{}。另一个返回*int。这些类型不能相互分配

使用此函数可将函数的结果一般附加到切片:

func Append(sp interface{}, f interface{}) {
    s := reflect.ValueOf(sp).Elem()
    s.Set(reflect.Append(s, reflect.ValueOf(f).Call(nil)[0]))
}
可以这样称呼:

var ints []*int
Append(&ints, ReturnInt)
如果参数不是指向切片的指针,或者函数未返回可分配给切片元素的值,则函数将死机


为什么不用append呢?它已经是通用的。例如,您可以这样做。还要注意的是,除了一些内置项外,Go不支持泛型,因此在Go程序中实现泛型类型的尝试将导致失败或缺少解决方案。为什么要投反对票?我很清楚go中的泛型情况,但是有适当的时间使用它。在本例中,它是一个单独的、非常孤立的、小的函数,可以解锁许多其他的清洁功能,并且在我的应用程序的其余部分都像习惯用法一样。对我来说,这是一个适当的权衡。Jared仅供参考,我不是投你反对票的人,所以我不能回答你的问题。至于你其余的评论:很公平。很快:谢谢,这正是我需要的。