Go 函数类型, 可重用的函数签名(译)

2,602 阅读1分钟

我一直在Golang中查找不同函数可重用的通用签名,google了好久没有找到。

我以自认为应该是正确的方式尝试“启发式的”编写代码来让编译器给我一些有用的提示。

多次尝试后。。。代码可以执行了。

你可以通过类型声明一个函数签名:

type myFunctionType = func(a, b string) string

下面是一个示例:

package main

/*  翻译自如下URL(译者注):
    https://medium.com/@kandros/go-function-type-reusable-function-signatures-2389f6bdd4f6
*/

import "fmt"

type myFunctionType = func(a, b string) string

func main() {
   var explicit myFunctionType = func(a, b string) string {
   	return fmt.Sprintf("%s %s", a, b)
   }

   implicit := func(a, b string) string {
   	return fmt.Sprintf("%s %s", b, a)
   }

   functionTypeConsumer(explicit)
   functionTypeConsumer(implicit)
   functionTypeConsumer(func(a, b string) string {
   	return fmt.Sprintf("%s %s", a, b)
   })
}

func functionTypeConsumer(fn myFunctionType) {
   s := fn("Hello", "World")
   fmt.Println(s)
}

这是一个在Go playground的演示示例

扩展阅读参见下面的文章(译者注):

1、 Go函数作为值与类型

2、 Function types and values