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

Rust项目bin目录添加模块报错,该如何正确布局使用?

问题描述

原项目结构:

/components/my_component/src/main.rs
                            /module.rs

修改为添加bin目录后的结构:

/components/my_component/src/bin/main.rs
                                /module.rs

编译时出现如下错误:

error[E0601]: `main` function not found in crate `my_module`
   --> my_component/src/bin/my_module.rs:568:2
    |
568 | }
    |  ^ consider adding a `main` function to `my_component/src/bin/my_module.rs`

Cargo会将src/bin下的每个.rs文件视为独立的二进制目标,因此module.rs被当作需要包含main函数的二进制 crate,从而触发错误。请问如何在这种目录布局下正常使用模块?

解决方法
  • 将共享模块移至src根目录
    把需要复用的module.rs放回src/根目录,这样src/bin/下的所有二进制文件都能通过use crate::module;导入使用。调整后结构:

    /components/my_component/src/module.rs
                              /bin/main.rs
    

    在src/bin/main.rs中导入模块:

    use crate::module;
    
    fn main() {
        // 调用module中的功能
    }
    
  • 在bin目录内使用相对路径导入
    若不想移动文件,可将module.rs作为bin/main.rs的子模块,在main.rs中通过相对路径导入:

    // 方式1:声明模块并导入
    mod module;
    use module::*;
    
    // 方式2:相对路径引用
    use super::module;
    
    fn main() {
        // 使用模块内容
    }
    

    注意:这种方式下module.rs仅能被当前二进制文件使用,bin/下其他文件无法直接复用该模块。

  • 通过Cargo.toml指定编译目标
    如果src/bin/中存在不需要作为独立二进制的文件,可在Cargo.toml里明确指定要编译的二进制文件:

    [[bin]]
    name = "main"
    path = "src/bin/main.rs"
    

    这样Cargo只会编译src/bin/main.rs,module.rs不会被当作独立二进制处理,之后即可在main.rs中用相对路径导入它。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 03:53:12