Define a recursive function within a function in Go

后端 未结 2 1214
孤独总比滥情好
孤独总比滥情好 2020-11-30 11:14

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:

f         


        
相关标签:
2条回答
  • 2020-11-30 11:37
    var Function2 func(m int) int
    Function2 = func(m int) int {
        ...
    
    0 讨论(0)
  • 2020-11-30 11:44

    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.

    0 讨论(0)
提交回复
热议问题