即使文件存在,Rust 也找不到模块

标签 rust

我目前正在按照 Rust 手册学习 Rust,并且正在尝试实现 CLI。但是我稍微更改了 CLI 的原始实现,现在我有以下文件:

  • main.rs
  • lib.rs
  • 配置文件

在我的 main.rs 中,我通过执行以下操作导入 lib.rs:

use std::{error::Error, env};
mod lib;

fn main() -> Result<(), Box<dyn Error>> {
    let args: Vec<String> = env::args().collect();
    lib::main(args)
}

在我的 lib.rs 中,我通过这样做导入 config.rs:

use std::{
    fs,
    process,
    io::Error as IoError,
    error::Error
};
mod config;

// Some other code

pub fn main(args: Vec<String>) -> Result<(), Box<dyn Error>> {
    let config = config::Config::new(args).unwrap_or_else(|err| {
        println!("Problem parsing arguments: {}", err);
        process::exit(1);
    });

    // Some other code

    Ok(())
}

我的 config.rs 包含公开的 Config 结构:

pub struct Config {
    pub query: String,
    pub filename: String,
}

impl Config {
    pub fn new(args: Vec<String>) -> Result<Config, &'static str> {
        // Some code
    }
}

但是,一旦我尝试运行代码,编译器总是抛出相同的错误:

error[E0583]: file not found for module `config`
 --> src/lib.rs:7:1
  |
7 | mod config;
  | ^^^^^^^^^^^
  |
  = help: to create the module `config`, create file "src/lib/config.rs"

error[E0433]: failed to resolve: could not find `Config` in `config`
  --> src/lib.rs:16:26
   |
16 |     let config = config::Config::new(args).unwrap_or_else(|err| {
   |                          ^^^^^^ could not find `Config` in `config`

error: aborting due to 2 previous errors

Some errors have detailed explanations: E0433, E0583.
For more information about an error, try `rustc --explain E0433`.

当我尝试将 config.rs 移动到 lib 文件夹时,编译器也找不到该文件,它告诉我在 src 文件夹中创建一个 config.rs。

知道为什么 rust 找不到 config.rs 吗?

最佳答案

main.rs 是一个独立的 crate,库 crate 不叫 lib。这意味着

mod lib;

应该是

use your_crate_name;

但是 Cargo 隐式地为你做了这件事,所以你可以删除这行并写:

use std::{error::Error, env};

fn main() -> Result<(), Box<dyn Error>> {
    let args: Vec<String> = env::args().collect();
    your_crate_name::main(args)
//  ^^^^^^^^^^^^^^^
}

关于即使文件存在,Rust 也找不到模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67958566/

相关文章:

rust - 如何使用引用解构元组结构

rust - 人造丝为什么不需要Arc <_>?

reference - 如何避免在 Rust 中克隆一个大整数

rust - 无法创建使用文字零的通用函数

rust - pub 和 pub(super) 什么时候有不同的语义?

vector - 为什么 borrow checker 提示这些不同切片的生命周期?

rust - 我可以获得 Rust 链接的原生工件的完整路径吗?

rust - 在使用rust 中,我如何在一行中进行这种类型转换

vector - 有没有办法获取向量的每个 n * i 元素?

rust - Solana Rust 智能合约如何获得区 block 高度或 Unix 时间?