I found something interesting in Go. Let's say I have my package name is mypkg
, inside mypkg
, I have two functions:
package mypkg
func MyFunc0(){
//...
}
var MyFunc1 = func(){
//...
}
Now in my main
package, it is possible to override MyFunc1
, like this:
mypkg.MyFunc1 = func(){
// new logic
}
However, it is not possible to override MyFunc0
the same way. So now a question is raised. What are the differences between the two ways of declaring a function? Is this behavior difference intended?
MyFunc0
is a function declaration (https://golang.org/ref/spec#Function_declarations)
MyFunc1
is not a function declaration. It is a variable (https://golang.org/ref/spec#Variable_declarations) of type func (see https://golang.org/ref/spec#Function_types, https://golang.org/ref/spec#Function_literals). It has an initial value, but can be changed to hold a different value/function (as long as function signatures match).
I learning go language (and English :P), and in the tour of go is a exersie: Fibonacci closure
(https://tour.golang.org/moretypes/22)
The result is: 0 1 1 2 3 5 8 13 21 34
The main function is:
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
And my first solution was:
func fibonacci() func() int {
antant := 0
ant := 1
i := 0
return func() int {
var result int
if i == 0 || i == 1 {
result = i
i++
return result
}
result = antant + ant
antant = ant
ant = result
return result
}
}
But I didn't want ask in heach call to f() if was the firsth or second call (if i == 0 || i == 1
). The result was a function auto-override:
type doFibonacci func(*doFibonacci) int
func fibonacci() func() int {
antant := 0
ant := 1
i := 0
doFibo := doFibonacci(func(ptrDo *doFibonacci) int {
var result int
if i == 0 || i == 1 {
result = i
i++
return result
}
*ptrDo = func(ptrDo *doFibonacci) int {
var result int
result = antant + ant
antant = ant
ant = result
return result
}
return (*ptrDo)(ptrDo)
})
return func() int {
return doFibo(&doFibo)
}
}
I apologize for my English.