2013-02-25 36 views
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) 
} 
+0

@thesystem編輯,'say'是'hello'。我想簡化的是在調用'ntimes'時消除匿名函數。 – demi 2013-02-25 01:40:19

+0

不,你不能。如果您始終知道要調用的方法,然後只傳入對象,或者您可以像在示例中一樣使用匿名函數包裝該方法,則可以使用接口。 – 2013-02-25 04:15:37

回答