【发布时间】:2013-10-12 04:10:00
【问题描述】:
来自 Golang.org http://golang.org/pkg/sort/
// By is the type of a "less" function that defines the ordering of its Planet arguments.
type By func(p1, p2 *Planet) bool
我从未见过这种结构。 func 是怎么出现在 type 之后的?这里的类型是什么?
我见过以下结构,但是
type aaaaaa interface { aaa() string }
type dfdfdf struct { }
从未见过
type By func(p1, p2 *Planet) bool
这在 Go 中怎么可能? type可以带interface、struct关键字以外的东西吗?
谢谢~!
【问题讨论】:
-
是的。例如,它也可以采用像
int这样的原始类型。type与 C/C++ 中的typedef关键字非常相似,只是参数颠倒了。 -
你的意思是,那么 func(p1, p2 *Planet) bool 现在是一个整体类型?
-
func(p1, p2 *Planet) bool是 Go 中函数指针的声明。如果您可以绕过反转的参数/类型,这与 the style used by C/C++typedefstatement 将函数指针声明为类型是一致的。 -
它不是函数指针。这只是一个功能。 go 中的函数是第一类类型,不需要有指向它们的指针。将这些视为 typedef 也不完全正确。它是 go 中的完整类型,就像 type Foo struct{} 一样。
标签: go