dongzao9044 2015-02-17 22:27
浏览 55
已采纳

Golang函数和函数变量语义

Why can't I define a recursive function as a variable? I seem to be able to define arbitrary functions except when they recurse.

This is legal:

func f(i int) int {
    if i == 0 {
        return 1
    }
    return i * f(i-1)
}

func main() {
    fmt.Println(f(2))
}

This is illegal:

var f func(int) int = func(i int) int {
    if i == 0 {
        return 1
    }
    return i * f(i-1)
}

func main() {
    fmt.Println(f(2))
}

This is legal and I'm guessing it is just because you can figure out f after initialization:

func main() {
    var f *func(int) int;
    t := func(i int) int {
        if i == 0 {
            return 1
        }
        return i * (*f)(i-1)
    }
    f = &t
    fmt.Println((*f)(2))
}

So it looks like it comes down to function and variable declarations of a function type are treated differently though from the reading the documentation I wouldn't expect that to be the case. Did I miss the part of the documentation detailing this?

I would expect the illegal case to work just because it works in other languages. Like in JavaScript:

(function () {
  var f = function (i) {
    if (i == 0) {
      return 1;
    }
    return i * f(i - 1);
  };

  console.log(f(2));
})();
  • 写回答

1条回答 默认 最新

  • doupian9490 2015-02-17 22:45
    关注

    The below code would be the preferred way of doing what you describe. Note that you do not have to create an additional variable, nor do you have a pointer to a function:

    package main
    
    import "fmt"
    
    func main() {
        var f func(int) int
        f = func(i int) int {
            if i == 0 {
                return 1
            }
            return i * f(i-1)
        }
        fmt.Println(f(2))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格