Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a recursive call in defer be optimized by the compiler?

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.

like image 648
Rahul Avatar asked Oct 26 '25 10:10

Rahul


1 Answers

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
}
like image 65
Francois Avatar answered Oct 29 '25 00:10

Francois



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!