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

Rust自定义链表测试模块导入错误问题求助

解决Rust测试中无法导入自定义链表模块的问题

核心原因

tests/ 目录下的每个文件都是独立的二进制 crate,无法直接访问 src/main.rs 中的模块——main.rs 是项目的二进制入口,其内部代码默认对外不可见。只有 src/lib.rs 中导出的模块才能被 tests 目录的测试 crate 引用。

解决方案

不需要修改 main.rs,而是调整模块结构让测试能正确引用:

  1. 创建/修改 src/lib.rs
    如果你的项目还没有 lib.rs,新建一个;如果已有,确保其中包含对链表模块的导出:

    // src/lib.rs
    // 若链表代码在 src/linked_list.rs 文件中
    pub mod linked_list;
    
    // 可选:直接导出 LinkedList 简化测试中的导入路径
    pub use linked_list::LinkedList;
    
  2. 修正测试文件的导入路径
    在 tests/linked_list.rs 中,需要以你的项目名称(对应 Cargo.toml 里的 name 字段)作为根路径导入:

    // tests/linked_list.rs
    // 假设项目名称是 "my_linked_list"
    use my_linked_list::linked_list::LinkedList;
    
    // 如果在 lib.rs 中用了 pub use,可简化为
    // use my_linked_list::LinkedList;
    
    #[test]
    fn test_new_list() {
        let mut list = LinkedList::new();
        // ... 测试逻辑
    }
    
  3. 验证运行
    执行 cargo test,此时测试应该能正确识别 LinkedList 类型。

额外说明

如果你的 main.rs 需要使用链表模块,只需在 main.rs 中通过 crate 路径引用:

// src/main.rs
use crate::linked_list::LinkedList;

fn main() {
    let mut list = LinkedList::new();
    // ... 业务逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:27:12