I'm relatively new to go
. I'm trying to write a generic "appender" function. This is a simplification, but its an attempt to create a clean interface for processing some lists. Specifically, I have questions about the two errors that this generates:
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
ReturnInt
be of type GenericFunc
? If this doesn't work, I'm not understanding how interface{}
can be used with functions at all.. can it?GenericFunc
returns the same type that the slice is, but after that appending should be possible.The types func() *interface{}
(type type of GenericFunc) and (type func() *int)
(the type of ReturnInt) are different types. One returns a *interface{}
. The other returns a *int
. The types are not assignable to each other.
Use this function to generically append the result of a function to a slice:
func Append(sp interface{}, f interface{}) {
s := reflect.ValueOf(sp).Elem()
s.Set(reflect.Append(s, reflect.ValueOf(f).Call(nil)[0]))
}
Call it like this:
var ints []*int
Append(&ints, ReturnInt)
The function will panic if the argument is not a pointer to a slice or the function does not return a value assignable to a slice element.