我知道函數(shù)可以作為參數(shù)傳遞。但我想使用一個函數(shù),該函數(shù)采用實現(xiàn)接口的類型作為函數(shù)的輸入。這還有可能嗎?我已經(jīng)嘗試了以下,它給出cannot use myfn1 (type func(int)) as type fn in argument to test了錯誤。package mainimport "fmt"type intf interface{}type fn func(i intf)func myfn1(i int) { fmt.Printf("\ni is %v", i)}func myfn2(i int) { fmt.Printf("\ni is %v", i)}func test(f fn, val int) { f(val)}func main() { test(fn(myfn1), 123) test(myfn2, 321)}你可以試試: https: //play.golang.org/p/Al7USxzmYST更改type fn func(i intf)為type fn func(i int)當然可以解決問題。但我不明白它是否可以與界面一起使用。
1 回答

胡子哥哥
TA貢獻1825條經(jīng)驗 獲得超6個贊
您可以將任何類型的函數(shù)作為參數(shù)傳遞。但是,當您將函數(shù)作為參數(shù)傳遞時,函數(shù)簽名必須匹配。因此,您不能傳遞采用接口的函數(shù)來代替采用 int 的函數(shù)。
將接口值傳遞給函數(shù)與傳遞 int 不同。當您調(diào)用具有 int 值的函數(shù)時,它只是傳遞該值。但是當你將一個 int 值傳遞給一個獲取 interface{} 的函數(shù)時,它必須創(chuàng)建一個包含值類型和值本身的接口值,然后傳遞它。
- 1 回答
- 0 關注
- 224 瀏覽
添加回答
舉報
0/150
提交
取消