开发者

How do I hold onto a factory function in Go?

开发者 https://www.devze.com 2023-03-03 13:03 出处:网络
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:

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.ne开发者_运维问答wFunc = 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?


package main

type Adder interface {
    Add(Adder)
    Val() int
}

type FuncAdder func() Adder

type Holder struct {
    FuncAdder
    SomeOtherData string
}

type number int

func (n *number) Add(a Adder) {
    *n += number(a.Val())
}

func (n *number) Val() int {
    return int(*n)
}

func NumberAdder() Adder {
    return Adder(new(number))
}

func main() {
    var holders []Holder
    var holder Holder
    holder.FuncAdder = NumberAdder
    holder.SomeOtherData = "SomeOtherData"
    holders = append(holders, holder)
}
0

精彩评论

暂无评论...
验证码 换一张
取 消