I'm trying to hold a function that will return new instances of a type implementing a particular interface in a struct. Here's a stripped down example:
package main
type Adder interface {
Add(Adder)
Val() int
}
type NewAdder func() Adder
type number int
type NewHolder struct {
newFunc NewAdder
}
func (me *number)Add(it Adder) {
*me += number(it.Val())
}
func (me *number)Val() int {
return int(*me)
}
func newAdder() *number {
return (*number)(new(int))
}
func main() {
var holder NewHolder
holder.newFunc = NewAdder(newAdder)
}
When I try to compile it, it says cannot convert newAdder (type func() *number) to type NewAdder
. So what's the go-like way to accomplish my goal?
Here's a Python example of what I'm trying to do, just for reference:
class NewStuffMaker(object):
def __init__(self, new):
self.new = new
def make_new():
return []
obj = NewStuffMaker(make_new)
new_lst = obj.new()
Ideally, I'd like to be able to hold a bunch of these functions (or structs containing the functions and some other data) in a slice. Is that an unreasonable thing to do?