3
我可以设置函数指针来使接收器的功能比创建函数更简单吗?Go:函数指针与接收函数的功能
package main
import "fmt"
type hello struct {
name string
}
func (obj *hello) hello() {
fmt.Printf("Hello %s\n", obj.name)
}
func ntimes(action func(), n int) {
for i := 0; i < n; i++ {
action()
}
}
func main() {
obj := hello{"world"}
// Can I do following simpler?
ntimes(func() {obj.hello();}, 3)
}
@thesystem编辑,'say'是'hello'。我想简化的是在调用'ntimes'时消除匿名函数。 – demi 2013-02-25 01:40:19
不,你不能。如果您始终知道要调用的方法,然后只传入对象,或者您可以像在示例中一样使用匿名函数包装该方法,则可以使用接口。 – 2013-02-25 04:15:37