Rust 在测试中的 println 中给出“堆栈溢出”错误

wal*_*eek 0 rust

谁能解释为什么这段代码在简单的 println 语句中给出错误?

fn set() -> String {
    String::from("Foo")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn set() {
        println!("{:?}", set());
        assert!(true)
    }
}
Run Code Online (Sandbox Code Playgroud)

给出以下错误

thread 'tests::set' has overflowed its stack
fatal runtime error: stack overflow
Run Code Online (Sandbox Code Playgroud)

cdh*_*wie 6

因为你的测试函数被调用setprintln!("{:?}", set())导致无限递归。本地模块中声明的符号取代使用use.

相反,使用println!("{:?}", super::set())来指示您要调用set父模块中的函数。

或者,您可以将测试函数称为 以外的其他函数set,或者通过执行 eg ,然后调用而不是set从父作用域以不同的名称导入。use super::set as real_setreal_set()set()