dttl3933 2019-03-20 20:54
浏览 85
已采纳

编译器是否可以优化递归调用?

Let's say I have this function:

func abc(i int) (e error) {
    defer func() {
        if r := recover(); r != nil {
            abc(i * 2)
        }
    }()

    if someCondition(i) {
      return fmt.Errorf("Some Err");
    }

    return action() // returns err (nil in case of success) or panics
}

Will this be considered a tail-recursive call? Can it be optimized by the compiler, as tail-recursive calls may be optimized?

I understand that suppressing panic in such a way is not a good decision, but assume there is a correct condition() function, which is safe and correctly determines when to quit.

  • 写回答

2条回答 默认 最新

  • duanchen1937 2019-03-20 23:43
    关注

    Two things to say here:

    • recover() will get value passed to a panic. In your case, unless someCondition panics, recover will always return nil. So I'm not sure what you are trying to do.
    • Go doesn't do tail call optimization, the go team prefers meaningful stacktraces. There are discussions about it but nothing agreed yet.

    If what you are trying to do is multiply i * 2 until condition is true, then just do:

    // using recursion
    func abc(i int) error {
        if err := someCondition(i); err != nil {
          return abc(i * 2);
        }
        return nil
    }
    
    // using loop
    func abc(i int) error {
        for someCondition(i) != nil {
            i *= 2
        }
        return nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部