在 Golang 中使用类型别名声明函数

Att*_*lio 4 function go type-alias

在 Golang 中可以做这样的事情吗?

package main

import "fmt"

type myFunType func(x int) int

var myFun myFunType = myFunType { return x }  // (1) 

func doSomething(f myFunType) {
    fmt.Println(f(10))
}

func main() {
    doSomething(myFun)
}
Run Code Online (Sandbox Code Playgroud)

换句话说,是否可以使用函数类型别名声明函数类型变量而不重复签名?或者,有没有办法在创建函数类型的变量时不总是重新输入整个函数签名

上面的代码示例,我希望它等同于下面的代码示例(用 line 替换(1)line (2)),导致编译错误syntax error: unexpected return, expecting expression

package main

import "fmt"

type myFunType func(x int) int 

var myFun myFunType = func(x int) int { return 2 * x } // (2)

func doSomething(f myFunType) {
    fmt.Println(f(10))
}

func main() {
    doSomething(myFun)
}
Run Code Online (Sandbox Code Playgroud)

icz*_*cza 5

来自规范:函数文字:

FunctionLit = "func" Signature FunctionBody .
Run Code Online (Sandbox Code Playgroud)

函数文字必须包含func关键字和签名。语法不允许使用函数类型。

同去的函数声明:

FunctionDecl = "func" FunctionName Signature [ FunctionBody ] .
Run Code Online (Sandbox Code Playgroud)

不允许使用函数类型(而不是签名)。

所以不,你想要的是不可能的。其原因是因为签名(函数类型)不包括参数名称(只是它们的顺序和类型),但是当您实际“创建”一个函数值时,您需要一种引用它们的方法,并且只有函数类型,你没有参数的名称。

更多详情请查看相关问题:

在 Golang 中获取方法参数名称

未命名参数在 Go 中是一回事吗?