在 Go 中,您可以將函數作為參數傳遞,例如callFunction(fn func). 例如:package mainimport "fmt"func example() { fmt.Println("hello from example")}func callFunction(fn func) { fn()} func main() { callFunction(example)}但是當它是結構的成員時是否可以調用函數?下面的代碼會失敗,但給你一個我在說什么的例子:package mainimport "fmt"type Example struct { x int y int}var example Examplefunc (e Example) StructFunction() { fmt.Println("hello from example")}func callFunction(fn func) { fn()} func main() { callFunction(example.StructFunction)}(我知道我在那個例子中要做的事情有點奇怪。我遇到的確切問題并沒有很好地縮小到一個簡單的例子,但這就是我的問題的本質。但是我也很感興趣這是從學術角度)
3 回答

尚方寶劍之說
TA貢獻1788條經驗 獲得超4個贊
Go 1.0 不支持使用綁定方法作為函數值。Go 1.1 將支持它,但在那之前您可以通過閉包獲得類似的行為。例如:
func main() {
callFunction(func() { example.StructFunction() })
}
它不太方便,因為您最終復制了函數原型,但應該可以解決問題。

交互式愛情
TA貢獻1712條經驗 獲得超3個贊
我修復了你的編譯錯誤。
package main
import "fmt"
type Example struct {
x, y float64
}
var example Example
func (e Example) StructFunction() {
fmt.Println("hello from example")
}
func callFunction(fn func()) {
fn()
}
func main() {
callFunction(example.StructFunction)
}
輸出:
hello from example
- 3 回答
- 0 關注
- 203 瀏覽
添加回答
舉報
0/150
提交
取消