【问题标题】:Golang : type By in Go?Golang:在 Go 中输入 By?
【发布时间】: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++ typedef statement 将函数指针声明为类型是一致的。
  • 它不是函数指针。这只是一个功能。 go 中的函数是第一类类型,不需要有指向它们的指针。将这些视为 typedef 也不完全正确。它是 go 中的完整类型,就像 type Foo struct{} 一样。

标签: go


【解决方案1】:

type By func(p1, p2 *Planet) bool 是从函数值定义类型的示例。

我们可以通过创建一个新的By 值并使用fmt.Printf 打印类型来看到这一点。在下面的示例中,我将 Planet 作为字符串 - 类型对于示例而言并不重要。

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()
}

输出:

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

编辑:根据 nemo 的评论更新。 new 关键字返回一个指向新值的指针。 func 并没有像我想的那样返回一个函数指针,而是返回一个函数值。

【讨论】:

  • *func() 是指向函数值的指针。 func() 只是一个函数值。术语函数指针起源于 C 语言,不应用于 go IMO 中的函数值。
  • @nemo - 你是对的。我已更新答案以反映您的建议。
【解决方案2】:

您可以使用任何基本类型(包括另一个用户定义的类型)在 go 中定义新类型。

例如,如果您定义一个新类型 File

type File struct {}

用一些方法

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

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

然后你可以定义一个新的类型叫做:

type SpecialFile File

并在其上定义自己的不同方法。

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

需要注意的重要一点是 SpecialFile 类型没有 Size 方法,即使它的基本类型是 File。您必须将其转换为 *File 才能调用 Size 方法。

如果您想要甚至不在同一个包中的类型,您甚至可以为您甚至不拥有的类型执行此操作。

【讨论】:

    猜你喜欢
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 2013-11-27
    • 2018-03-20
    • 1970-01-01
    • 2022-10-14
    相关资源
    最近更新 更多