Trouble with implementing minigrep from the Rust documentation

I've been attempting to follow along with the minigrep implementation in the Rust documentation, but I've hit a wall at refactoring in part 12.3. I separated the config run code into a library subcrate, but whenever I try to run the code as is, it spits back "use of undeclared crate or module minigrep", I've tried making a subcrate labeled "minigrep", I've tried messing with cargo.toml, nothing seems to work. What am I doing wrong?

minigrep

  • config
    • src
      • lib.rs
    • Cargo.toml
  • src
    • main.rs
  • target
  • Cargo.lock
  • Cargo.toml

As part of my troubleshooting attempt, I copy-pasted the code to make sure there was zero differences, but for clarity the code of my main.rs file is as follows:

use std::env;
use std::process;

use minigrep::Config;

fn main() {
    let args: Vec<String> = env::args().collect();
    
    let config = Config::build(&args).unwrap_or_else(|err| {
        println!("Problem parsing arguments: {err}");
        process::exit(1);
    });

    println!("Searching for {}", config.query);
    println!("In file {}", config.file_path);

    if let Err(e) = Config::run(config) {
        println!("Application error: {e}");
        process::exit(1);
    }
}

You created a config crate. The book describes two files in the src directory. lib.rs for the library code and main.rs for the executable.

1 Like

Strange, that worked. Why would it say that minigrep is an undeclared crate because of that?

To understand this, it's helpful to keep straight the difference between crates and packages (which is unfortunately often confused).

  • A crate is a collection of Rust code that the Rust compiler can compile, or previously compiled and is now using as a dependency. Crates are a Rust language concept.
  • A package is a directory containing a Cargo.toml manifest file[1], which Cargo (not the compiler) takes as instructions for how to build one or more crates.

In order for use minigrep::Config; to succeed, there must be a library crate named minigrep which the current crate depends on. In the layout you started with, there was no library crate named minigrep; only a library crate named config, and also you probably didn't declare a dependency on it either.

When you have lib.rs in a package, defining a library crate, Cargo automatically makes that crate available to all binary crates defined by that package. That's why, in the intended arrangement, use minigrep::Config automatically succeeds without any further work (given that the package's name is minigrep). If you want to use any other library crates than that one (and std) then you have to declare them in [dependencies].


  1. that is not a workspace manifest instead ↩ī¸Ž

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.