I want to be able to return a recursive anonymous function in golang. I have used the code snippet below. Here foo() doesn't work because the anonymous function has no way of referring to itself. bar() works as expected.
What would be the right way of doing this, if at all possible?
package main
import (
"fmt"
)
func foo() func(int) int {
return func(x int) int {
if x == 1 {
return 1
}
return x * func(x-1) // this is where the problem lies
}
}
func bar() func(int) int {
return func(x int) int {
return x * 100
}
}
func main() {
a:= foo()
b:= bar()
fmt.Println(a(5))
fmt.Println(b(5))
}