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.
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.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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With