在Go中,可以將函數作爲參數傳遞,如callFunction(fn func)
。例如:使用函數名稱作爲參數
package main
import "fmt"
func example() {
fmt.Println("hello from example")
}
func callFunction(fn func) {
fn()
}
func main() {
callFunction(example)
}
但是當它是一個結構的成員時可以調用一個函數嗎?下面的代碼會失敗,但給你的,我說的是什麼一個例子:
package main
import "fmt"
type Example struct {
x int
y int
}
var example Example
func (e Example) StructFunction() {
fmt.Println("hello from example")
}
func callFunction(fn func) {
fn()
}
func main() {
callFunction(example.StructFunction)
}
(我知道我想在這例子做的是一個有點古怪的具體問題,我已經沒有按雖然我不是一個簡單的例子,但是這是我的問題的本質,但我從學術角度也對此感興趣)
我沒有試圖編譯該代碼,它是我直接編碼到SO中的問題的模擬。所以,軟件包/程序和x/y類型的錯誤只是缺乏頭腦,而不是我原來的代碼問題。 我很疑惑你是如何得到輸出的,因爲你的代碼的失敗方式與我的做法一樣:'method example.StructFunction不是一個表達式,必須調用'[編輯] ahh問題是Go的版本我正在運行(1.0.3)不支持它。提示確實。 – laumars 2013-04-09 13:57:11
'$ go version' 'go version devel + 1a196137ed09 Tue Apr 09 18:17:55 2013 +1000 linux/amd64'這是否意味着Go現在可以做你想做的事了? – peterSO 2013-04-09 14:14:29
還沒有,但是當1.1推出我的回購,那麼它會。鑑於這一週只有幾個星期,我很樂意等待。 – laumars 2013-04-09 14:26:56