Answer the question
In order to leave comments, you need to log in
Golang: How does the func type work?
If in golang we need to make a closure, we will write:
closureFunc := func () someReturnType {
/* function body */
return valueOfSomeReturnType;
}
func () someReturnType
package main
import "fmt"
type SoneFuncType func() bool
func main() {
var someInstance SomeFuncType
fmt.Printf("%+v",someInstance);
}
Answer the question
In order to leave comments, you need to log in
In the second variant, it looks like this . To declare the body of a function, you need to use the func keyword.and nothing else, which is reasonable for its own reasons. At a minimum, you do not need to remember and keep in mind which signature is behind which type when you look at the function body, that is, for each function body, you can clearly see what it should accept and return. In addition, additional flexibility (in this case: declaring a function through type aliases, rather than the func keyword) is always a performance hit, in this case, a likely increase in compilation time, and for language developers this is one of the main factors, because they are very, very picky about all the introductions and features of the compiler. Look, they can’t even interrogate generics from them. Moreover, the benefit of being able to declare a function body via type aliases rather than the func keyword is highly questionable, Don't you think so? Also, don't confuse a type declaration with a function declaration. It is logical that the type must always be declared first, and then the function / variable / structure itself, just the syntax of the language allows you to reduce the scribbling. And you in the given situation want to manage only creation of type. And how then will you name the input parameters of the function when it is declared, if any?
The benefit is exactly the same as with other options for using type aliases. First of all , this is the possibility of additional type control.
For example: You are developing a library (your package) and you need some function to receive as input only those functions that are defined in your library and no others. Then you create a type alias to the function signature and make it invisible to external consumers (declare it with a small letter).
package mylib
type someFunc func() bool
var (
Apple someFunc = func() bool {
return true
}
Dog someFunc = func() bool {
return false
}
)
func Consume(f someFunc) {
f()
}
package main
import "mylib"
func main() {
externalFunc := func() bool {
return true
}
mylib.Consume(externalFunc) // fail
var extF mylib.someFunc // fail
mylib.Consume(mylib.Apple) // success
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question