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

huangapple go评论88阅读模式
英文:

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

问题

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

type mapFunc func(value int) int

你能否使用这个类型声明一个函数而不重复它?类似于:

doubleIt := mapFunc {
    return 2*value
}
英文:

Suppose you declare a function type

type mapFunc func(value int) int

Can you declare a function by using this type without duplicating it? Something like:

doubleIt := mapFunc {
    return 2*value
}

答案1

得分: 4

据我所知,目前最简洁的方式仍然是:

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

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

不需要额外的转换,比如doubleId := mapFunc(func...),这是因为根据type identity规则:

如果两个函数类型具有相同数量的参数和结果值,对应的参数和结果类型相同,并且两个函数都是可变参数或都不是可变参数,则它们是相同的。参数和结果的名称不需要匹配。

英文:

As far as I know, the shortest way is still:

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

So it's not getting any shorter, and I don't think it would be more readable to decouple the function signature from its body. The benefit of declaring a named func type is using it in other declarations.

No extra conversions like doubleId := mapFunc(func...) needed, because of the type identity rules:

> 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.

答案2

得分: 1

当然,你可以将func作为一个一等公民类型来使用,就像其他预声明的类型一样。尽管以这种方式声明它并没有太多意义:

package main

import "fmt"

// 对于命名类型,你不需要命名参数
type mapFunc func(int) int

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

这个示例说明了在Go语言中,函数只是另一种类型,可以像其他命名类型一样对待。

英文:

Of course you can func is a first-class type like any other pre-declared types, although it doesn't make much sense to declare it this way:

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
}

This is to illustrate that function is just another type in Go and can be treated like any other named type.

huangapple
  • 本文由 发表于 2015年2月22日 03:36:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/28650394.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定