【发布时间】:2013-06-10 14:58:20
【问题描述】:
我有这两种类型:
type Routing map[string]Handler
type Handler interface {
Handle()
}
我有一个类型叫MyHandler,它满足接口,它看起来像这样:
type MyHandler struct {
}
func (this *MyHandler) Handle() {
// ...
}
我希望能够做这样的事情:
// routes is created at the beginning of the program and available
// throughout the lifetime of the script
routes := Routing {
"/route/here": MyHandler,
})
// ...
// and in another method, this line may be executed several times:
new(routes["/route/here"]).Handle()
我在最后一行收到此错误:
routes["/route/here"] 不是类型
当我将最后一行更改为
routes["/route/here"].Handle()
它显然有效。但是,它永远只使用 Handler 的一个实例......我希望每次执行最后一行时都有一个新实例。每次执行最后一行时,如何实例化 Handler 的新实例?
(我假设在使用new 时,旧的将在使用后被垃圾回收。请注意,我没有保存我创建的实例;我只关心调用Handle() 方法然后将其销毁.)
【问题讨论】:
-
也许
Routing应该是type Routing map[string](func() Handler)然后你可以把NewMyHandler函数放到map 中,每次调用它都会返回一个新函数? -
好主意。你应该把这个作为答案!
-
我几乎不知道我在 Go 中在说什么,所以我害怕 :P 幸运的是其他人完成了所有艰苦的工作来填写细节。