dtwvr26066 2015-01-22 21:58
浏览 55
已采纳

在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

  • 写回答

2条回答 默认 最新

  • 普通网友 2015-01-22 22:02
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址