我想實例化一堆相同類型的函數,而不必復制它們的簽名。我已經有一個描述該簽名的函數類型(fancyFunc如下)和另一個使用此類參數的函數(doFancyStuff如下)。我將如何做這樣的工作?package mainimport "fmt"type fancyFunc func(a,b,c int) intfunc doFancyStuff(f FancyFunc) int { // Do something special with f return 42}func main() { // This works but is rather tedious: f1 := func(a,b,c int) int { return a + b + c } // I would like to create them like this: f2 := fancyFunc{ return a * b * c } // Eventually, they are used like this: fmt.Println(doFancyStuff(f1)) fmt.Println(doFancyStuff(f2))}
1 回答

慕碼人2483693
TA貢獻1860條經驗 獲得超9個贊
你只能按照案例來做f1
,或者定義一個普通的函數。沒有什么比這更好的f2
方式了。在 C 中,人們使用宏來做到這一點,但 Go 沒有預處理器(你可以使用一些非官方的預處理器)。
- 1 回答
- 0 關注
- 145 瀏覽
添加回答
舉報
0/150
提交
取消