Reputation: 481
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
}
Upvotes: 1
Views: 104
Reputation: 8390
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.
Upvotes: 1
Reputation: 34282
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.
Upvotes: 4