How to implement a generic slice appender?
我对
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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: first argument to append must be slice; have interface
{} prog.go:15:11: cannot use ReturnInt (type func() *int) as type
GenericFunc in argument to Append
《
使用这两个功能generically append结果的两个功能:一片
1 2 3 4 | func Append(sp interface{}, f interface{}) { s := reflect.ValueOf(sp).Elem() s.Set(reflect.Append(s, reflect.ValueOf(f).Call(nil)[0])) } |
这样的信息:呼叫
1 2 | var ints []*int Append(&ints, ReturnInt) |
"如果这个功能会恐慌的说法冰槽的两个螺旋的指针或函数不返回一个值assignable两个螺旋元件。
playground example