I am trying to define a recursive function within another function in Go but I am struggling to get the right syntax. I am looking for something like this:
func Function1(n) int {
a := 10
Function2 := func(m int) int {
if m <= a {
return a
}
return Function2(m-1)
}
return Function2(n)
}
I'd like to keep Function2 inside the scope of Function1 as it is accessing some elements of its scope.
How can I do this in Go?
Many thanks
You can't access
Function2
inside of it if it is in the line where you declare it. The reason is that you're not referring to a function but to a variable (whose type is a function) and it will be accessible only after the declaration.Quoting from Spec: Declarations and scope:
In your example
Function2
is a variable declaration, and the VarSpec is:And as the quote form the language spec describes, the variable identifier
Function2
will only be in scope after the declaration, so you can't refer to it inside the declaration itself. For details, see Understanding variable scope in Go.Declare the
Function2
variable first, so you can refer to it from the function literal:Try it on Go Playground.