如何保留 Go 中的工厂函数?
我试图保存一个函数,该函数将返回在结构中实现特定接口的类型的新实例。这是一个精简的示例:
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)
}
当我尝试编译它时,它说 cannot conversion newAdder (type func() *number) to type NewAdder
。那么实现我的目标的类似方法是什么?
这是我正在尝试做的一个 Python 示例,仅供参考:
class NewStuffMaker(object):
def __init__(self, new):
self.new = new
def make_new():
return []
obj = NewStuffMaker(make_new)
new_lst = obj.new()
理想情况下,我希望能够在切片中保存一堆这些函数(或包含函数和一些其他数据的结构)。这样做是不是很不合理?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)