在走,如果你定義一個新的類型例如爲:爲什麼我可以輸入別名函數並在不投射的情況下使用它們?
type MyInt int
你不能再通過一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
鍵入MyFunc
,因爲我會在第一個例子做;它似乎不一致。我確信有一個很好的理由。任何人都可以啓發我嗎?
我想問的原因,主要是因爲我想縮短我的一些相當長的函數類型的這種方式,但我想,以確保它的預期和可接受做到這一點:)
**在走,沒有這樣的事,作爲一個'型alias' **的'type'關鍵字引入新命名的類型。他們不是別名。 (這是Go與其他各種語言相比的重要優勢之一) –
@ Rick-777存在類型別名,例如'byte'是'uint8'的別名,'rune'是'int32'的別名,但是確實'type'關鍵字不會生成別名,而是新的類型。 – icza
是的,謝謝指出 - 有兩種特殊情況:字節和符文。這些*是*別名,但不可能創建任何新的別名。 https://golang.org/ref/spec#Numeric_types –