Golang:在Go中输入By吗?

This is from 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

I've never seen this structure. How come func comes after type? And what is type here?

I've seen the following structures but

type aaaaaa interface { aaa() string }
type dfdfdf struct { } 

Never seen like

type By func(p1, p2 *Planet) bool

How this is possible in Go? type can take other things than interface, struct keywords?

Thanks~!

type By func(p1, p2 *Planet) bool is an example of defining a type from a function value.

We can see that by creating a new By value and printing the type using fmt.Printf. In the example below I stumped out Planet as a string - the type doesn't matter for the purposes of the example.

type.go

package main
import(
  "fmt"
  )

type Planet string
type By func(p1, p2 *Planet) bool

func main() {
  fmt.Printf("The type is '%T'", new(By))
  fmt.Println()
}

Output:

mike@tester:~/Go/src/test$ go run type.go
The type is '*main.By'

EDIT: Updated per nemo's comment. The new keyword returns a pointer to the new value. func does not return a function pointer like I had incorrectly thought but instead returns a function value.

You can define a new type in go with any base type including another user defined type.

For instance if you define a new type File

type File struct {}

with some methods

func (f *File) Close() { ... }

func (f *File) Size() { ... }

You could then define a new type called:

type SpecialFile File

and define your own different methods on it.

func (f *SpecialFile) Close() { (*File)(f).Close() }

The important thing to note is the SpecialFile type doesn't have a Size method on it even though it's base type is a File. You have to cast it to a *File in order to call the Size method.

You can do this for types you don't even own if you want that aren't even in the same package.