在 Go 中的函数内定义递归函数 [英] Define a recursive function within a function in Go

查看:40
本文介绍了在 Go 中的函数内定义递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 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)
}

我想将 Function2 保留在 Function1 的范围内,因为它正在访问其范围的某些元素.

I'd like to keep Function2 inside the scope of Function1 as it is accessing some elements of its scope.

如何在 Go 中执行此操作?

How can I do this in Go?

非常感谢

推荐答案

如果 Function2 位于声明它的行中,则无法访问其中的 Function2.原因是您指的不是函数,而是变量(其类型是函数),并且只有在声明之后才能访问它.

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.

引用自 规范:声明和范围:

在函数内部声明的常量或变量标识符的作用域从 ConstSpec 或 VarSpec(ShortVarDecl 为短变量声明)的末尾开始,并在最里面的包含块的末尾结束.

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.

在您的示例中 Function2 是一个变量声明,而 VarSpec 是:

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)
}

正如语言规范所描述的引用形式,变量标识符 Function2 只会在声明之后的范围内,因此您不能在声明本身内部引用它.有关详细信息,请参阅了解 Go 中的变量范围.

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.

首先声明 Function2 变量,以便您可以从 函数中引用它文字:

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)
}

Go Playground 上试试.

这篇关于在 Go 中的函数内定义递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆