1

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
}

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Wrapping with mapFunc is redundant due to the type identity rules.
Well @rfalke was asking in the context when he declared a function as named type. He might have had specific use. This is not common but simply to illustrate his point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.