You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust项目测试文件如何正确导入src目录下的模块源文件?

解决Rust测试文件中模块导入失败的问题

问题场景

项目结构如下:

.
├── Cargo.lock
├── Cargo.toml
├── demo.txt
├── src
│   ├── lib.rs
│   ├── lifetime_demo
│   │   └── mod.rs
│   ├── main.rs
└── tests
    └── trait_test.rs

src/lifetime_demo/mod.rs 代码:

pub mod lifetime_mod {
    pub fn show() {}
}

tests/trait_test.rs 代码:

use demo::lifetime_demo::lifetime_mod;
#[test]
fn test_trait() {
    lifetime_mod::show();
}

运行 cargo test 时出现错误:

error[E0432]: unresolved import `demo::lifetime_demo`
 --> tests/trait_test.rs:3:11
  |
3 | use demo::lifetime_demo::lifetime_mod;
  |           ^^^^^^^^^^^^^ could not find `lifetime_demo` in `demo`

解决方案

错误核心是**src/lib.rs 未公开导出 lifetime_demo 模块**,测试代码无法从 crate 根目录(lib.rs)访问到该模块。

只需修改 src/lib.rs,添加对 lifetime_demo 的公开声明:

// src/lib.rs
pub mod lifetime_demo;

Rust 会自动识别 lifetime_demo 目录下的 mod.rs 文件作为模块内容。修改完成后,重新运行 cargo test 即可成功导入模块并执行测试。

内容的提问来源于stack exchange,提问作者uwei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 07:22:12