在 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
,就像我在第一个示例中必须做的那样;它似乎不一致。我确信这是有充分理由的。谁能启发我?
我问的原因主要是因为我想以这种方式缩短一些相当长的函数类型,但我想确保这样做是可以预期和可以接受的:)