dttl3933 2019-03-21 04: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-21 07: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条)

报告相同问题?

悬赏问题

  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题