Define a recursive function inside a function in Go

I am trying to define a recursive function inside another function in Go, but I am struggling to get the correct 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 would like to leave Function2 inside the scope of Function1, as it accesses some elements of its scope.

How can i do this in go?

Thank you very much

+6
source share
2 answers

You cannot access Function2 inside it if it is in the line where you declare it. The reason is that you are not referring to a function, but to a variable (whose type is a function), and it will be available only after the declaration.

First declare a Function2 variable, so you can refer to it from a 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 the go playground .

+18
source
 var Function2 func(m int) int Function2 = func(m int) int { ... 
0
source

Source: https://habr.com/ru/post/981422/


All Articles