Define a recursive function within a function in Go

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.

Leave a Comment