【发布时间】:2020-09-01 10:31:04
【问题描述】:
几个小时以来,我一直试图了解如何导入函数以在 Rust 中进行测试,但没有成功。我的项目结构如下所示:
.
├── Cargo.lock
├── Cargo.toml
├── src
│ ├── main.rs
│ └── funcs
│ ├── mod.rs
│ └── hello.rs
└── tests
└── test_hello.rs
src/funcs/mod.rs:
pub mod hello;
src/funcs/hello.rs:
pub fn hello() {
println!("{}", "hello!");
}
src/main.rs:
mod funcs;
fn main() {
funcs::hello::hello(); // this works
}
src/tests/test_hello.rs
mod funcs; // this import does not work!
#[test]
fn add() {
assert_eq!(2 + 2, 4);
}
#[test]
fn hello_test() {
assert_eq!(funcs::hello::hello(), "hello");
}
如何在src 中导入公共函数,以便在我的测试目录中使用它们?
【问题讨论】:
-
mod定义一个模块;它不导入一个模块。使用use导入模块。应该类似于use crate::funcs;intest_hello.rs。 -
感谢您的帮助。当我在
test_hello.rs中使用use crate::funcs;时,出现错误:unresolved import crate::funcs no funcs in the root。我在main.rs中看到了mod funcs,所以我不确定这个错误是什么意思。 -
按照 Acorn 在下方评论中的建议,将
pub mod funcs;设置为main.rs。
标签: rust