在 Go 中,如果你定義了一個新類型,例如:type MyInt int然后您不能將 a 傳遞給MyInt需要 int 的函數,反之亦然:func test(i MyInt) { //do something with i}func main() { anInt := 0 test(anInt) //doesn't work, int is not of type MyInt}美好的。但是為什么這同樣不適用于函數呢?例如:type MyFunc func(i int)func (m MyFunc) Run(i int) { m(i)}func run(f MyFunc, i int) { f.Run(i)}func main() { var newfunc func(int) //explicit declaration newfunc = func(i int) { fmt.Println(i) } run(newfunc, 10) //works just fine, even though types seem to differ}現在,我不是在抱怨,因為它使我不必像在第一個示例中那樣顯式地強制轉換newfunc為 type MyFunc;它似乎不一致。我相信這是有充分理由的;任何人都可以啟發我嗎?我問的原因主要是因為我想以這種方式縮短一些相當長的函數類型,但我想確保這樣做是預期和可接受的:)
- 2 回答
- 0 關注
- 198 瀏覽
添加回答
舉報
0/150
提交
取消