Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a recursive function within a function in Go

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

like image 749
Spearfisher Avatar asked Jan 22 '15 21:01

Spearfisher


People also ask

Can you define a function within a function Go?

Nested functions are allowed in Go. You just need to assign them to local variables within the outer function, and call them using those variables.

Does Golang support recursion?

what is the golang recursive function. Recursion is a general programming code process in which the method or function calls itself continuously. Go Language support recursion using functions. function call itself is called a recursive function.

How do you define a recursive function?

A recursive function is a function that is defined in terms of itself via self-referential expression. That means the function calls itself and repeats the behavior until some condition is met, and then that will either return a result or in the case of the Santa Claus example, just print some value.


1 Answers

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:

The scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl for short variable declarations) and ends at the end of the innermost containing block.

In your example Function2 is a variable declaration, and the VarSpec is:

Function2 := func(m int) int {     if m <= a {         return a     }     return Function2(m-1) } 

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:

func Function1(n int) int {     a := 10     var Function2 func(m int) int      Function2 = func(m int) int {         if m <= a {             return a         }         return Function2(m - 1)     }      return Function2(n) } 

Try it on Go Playground.

like image 108
icza Avatar answered Sep 18 '22 12:09

icza