du8980919 2013-10-12 04:10
浏览 50
已采纳

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~!

  • 写回答

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.

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳