gpt4 book ai didi

rust - 如何从测试模块调用不在模块内的函数?

转载 作者:行者123 更新时间:2023-11-29 08:31:32 26 4
gpt4 key购买 nike

这些是我的 src/lib.rs 文件的内容:

pub fn foo() {}

#[cfg(test)]
mod tests {
#[test]
fn it_works() {
foo();
}
}

当我运行 cargo test 时,出现以下错误:

error[E0425]: cannot find function `foo` in this scope
--> src/lib.rs:7:9
|
7 | foo();
| ^^^ not found in this scope

如何从 test 模块中调用 foo

最佳答案

您可以使用 super:: 来引用父模块:

fn it_works() {
super::foo();
}

在 Rust 2015 中,您可以使用 :: 来引用 crate 的根模块:

fn it_works() {
::foo();
}

在 Rust 2018 中,您可以使用 crate:: 来引用 crate 的根模块:

fn it_works() {
crate::foo();
}

或者,由于 foo 可能被重复使用,您可以在模块中使用它:

mod tests {
use foo; // <-- import the `foo` from the root module
// or
use super::foo; // <-- import the `foo` from the parent module

fn it_works() {
foo();
}
}

对于测试模块,从父模块导入所有内容也很常见:

mod tests {
use super::*; // <-- import everything from the parent module

fn it_works() {
foo();
}
}

关于rust - 如何从测试模块调用不在模块内的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56572015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com