在Go中,如果您定义一个新类型,例如:
type MyInt int
Run Code Online (Sandbox Code Playgroud)
然后,您无法将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
}
Run Code Online (Sandbox Code Playgroud)
精细.但是为什么同样不适用于功能呢?例如:
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
} …Run Code Online (Sandbox Code Playgroud)