实现:https://github.com/samsieber/tco
这个思路很清奇——用属性宏来实现尾递归调用优化。官方的例子:
#[tco::rewrite]
fn fac_with_acc(n: u128, acc: u128) -> u128 {
if n > 1 {
fac_with_acc(n - 1, acc * n)
} else {
acc
}
}
优化后的代码为:fn fac_with_acc(n: u128, acc: u128) -> u128 {
let mut n = n;
let mut acc = acc;
'__tco_loop: loop {
return {
if n > 1 {
{
let __tco_0 = (n - 1, acc * n);
n = __tco_0.0;
acc = __tco_0.1;
continue '__tco_loop;
}
} else {
acc
}
};
}
}