du8980919 2013-10-12 04:10
浏览 50


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?


  • 写回答

2条回答 默认 最新

  • doutan5844 2013-10-12 04:31

    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.


    package main
    type Planet string
    type By func(p1, p2 *Planet) bool
    func main() {
      fmt.Printf("The type is '%T'", new(By))


    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
  • dongwen5019 2013-10-14 03:19

    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.




  • ¥15 关于#abap#的问题,请各位专家解答!
  • ¥20 内网通过公网访问外网问题
  • ¥20 谁有这个东西 继续教育的
  • ¥15 怎么使请求通过cors
  • ¥15 WDM 驱动ACPI 相关疑问
  • ¥15 prism 跨窗体共享数据绑定 wpf
  • ¥15 hdl designer突然用不了系统的moduleware组件,请问有人遇到或者怎么解决吗?
  • ¥15 0基础计算机毕设,应该从哪开始?
  • ¥60 使用DKT40脑图划分ROI区域
  • ¥15 有偿解决C51单片机液晶屏12864显示问题