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
- Why can't
ReturnInt
be of typeGenericFunc
? If this doesn't work, I'm not understanding howinterface{}
can be used with functions at all.. can it? - How can you accept a "generic" slice and append to it using reflection? This would involve checking that
GenericFunc
returns the same type that the slice is, but after that appending should be possible.