Rust cannot find module even though the file is present

Viewed 1349

I'm currently learning Rust by following the Rust Book and I'm trying to implement the CLI. But I changed the original implementation of the CLI a bit and now I have the following files:

  • main.rs
  • lib.rs
  • config.rs

In my main.rs, I import the lib.rs by doing the following:

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

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

In my lib.rs, I import the config.rs by doing this:

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(())
}

My config.rs contains the Config struct which is made public:

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

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

However, once I try to run the code, the compiler always throws the same error:

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`.

When I try to move the config.rs into a lib folder, the compiler cannot find the file as well and it tells me to create a config.rs in the src folder.

Any idea why rust can't find the config.rs?

1 Answers

main.rs is an independent crate and the library crate is not called lib. Together this means

mod lib;

should be

use your_crate_name;

but Cargo implicitly does it for you so you can remove the line and write:

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

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