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

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)