我有一个使用递归的Rust程序.有时它会遇到"堆栈溢出"运行时错误.我想阻止这种情况的发生.相反,我希望在我的递归函数中有如下内容:
fn foo() -> u32 {
if stack_is_almost_full() {
panic!("Something is wrong with the recursion!");
}
// continue normally
}
有可能吗?
我有一个使用递归的Rust程序.有时它会遇到"堆栈溢出"运行时错误.我想阻止这种情况的发生.相反,我希望在我的递归函数中有如下内容:
fn foo() -> u32 {
if stack_is_almost_full() {
panic!("Something is wrong with the recursion!");
}
// continue normally
}
有可能吗?
您可以从stacker::remaining_stack
得到剩余堆栈空间的估计值.
但是,对于检测递归问题,一些更直接的方法可能更合适:
const MAX_DEPTH: usize = 1024;
#[inline(always)]
fn foo() -> u32 {
foo_rec(0).expect("MAX_DEPTH reached while recursing")
}
fn foo_rec(depth: usize) -> Option<u32> {
if depth > MAX_DEPTH {
None
}
// do your work possibly recursing, finally return something
if should_recurse() {
foo_rec(depth + 1)
} else {
Some(42)
}
}
fn should_recurse() -> bool {
true // uh-oh
}