type FuncPtr func(int) int
func Foo(i int) { return i * i }
type Events struct {
SomeFunc FuncPtr
}
type Top struct {
events Events
}
func (self *Top) initEvents() {
// This change works within this function, but
// doesn't stick around after this method returns.
self.events.SomeFunc = Foo
}
func main() {
var t := Top{}
t.initEvents()
t.events.SomeFunc == nil // True: Change in initEvents() doesn't stick
}
如何在initEvents()
方法中保持更改?也就是说,我希望在Top::Events::SomeFunc
方法中更改函数引用initEvents()
的值,并在initEvents()
方法返回后将该更改粘贴。
答案 0 :(得分:0)
您使用的代码使用了一些小的更正来使其可编译。
为方便起见,我已经提供了以下代码的完整示例,如果您想自己运行,可以执行以下操作:https://play.golang.org/p/Ngu8FFiGrI
package main
import(
"fmt"
)
type FuncPtr func(int) int
func Foo(i int) int {
return i*i
}
type Events struct {
SomeFunc FuncPtr
}
type Top struct {
events Events
}
func (self *Top) initEvents() {
// This change works within this function, but
// doesn't stick around after this method returns.
self.events.SomeFunc = Foo
}
func main() {
var t = Top{}
t.initEvents()
if t.events.SomeFunc == nil {
fmt.Println("SomeFunc not set")
}
fmt.Println("6^2 =",t.events.SomeFunc(6))
}