如何在 GO 中使用函数类型声明函数

How can one declare a function using a function type in GO

假设你声明了一个函数类型

type mapFunc func(value int) int

你能在不复制的情况下使用这种类型声明一个函数吗?类似于:

doubleIt := mapFunc {
    return 2*value
}

据我所知,最短的路还是:

doubleIt := func (value int) int {
    return value * 2
}

所以它并没有变得更短,而且我认为将函数签名与其主体分离不会更具可读性。声明命名 func 类型的好处是在其他声明中使用它。

不需要像 doubleId := mapFunc(func...) 这样的额外转换,因为 type identity 规则:

Two function types are identical if they have the same number of parameters and result values, corresponding parameter and result types are identical, and either both functions are variadic or neither is. Parameter and result names are not required to match.

当然你可以 func 是一个 first-class 类型,就像任何其他预先声明的类型一样,尽管这样声明它没有多大意义:

package main

import "fmt"

// You need not a named argument for a named type
type mapFunc func(int) int

func main() {
        doubleIt := mapFunc(func(value int) int { return value * 2})
        fmt.Println(doubleIt(2))      // 4
}

这是为了说明函数只是 Go 中的另一种类型,可以像对待任何其他命名类型一样对待。