How to define a separate lib.rs in the same folder with main.rs

In the ebook "The rust programming language" chapter 12.3 "Refactoring to Improve Modularity and Error Handling" section "Splitting Code into a Library Crate" it said split the main.rs file and put some code into src/lib.rs file then move the /src/lib.rs into the scope of the binary crate by adding "use minigrep::Config;"

I m confusing here: it should use the same crate named minigrep, but how could I make it? I tried many ways but cannot make the result as tutorial. how to make a crate both binary and library?

Basically, lib.rs and main.rs will be the root of two entirely independent crate. The main.rs crate will have a dependency on the lib.rs crate, but not the other way around. So:

  • When accessing something in the library crate from the library crate, you import with use crate::.
  • When accessing something in the binary crate from the binary crate, you import with use crate::.
  • When accessing something in the libary crate from the binary crate, you import with use your_crate_name::.

Here, your_crate_name will be whatever name you used in your Cargo.toml file.

4 Likes

Thank you for detail reply, I fixed it!

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.