Using lib.rs from a tests.rs

I have written my first piece of useful rust code – filescan recursively descends into directories noting the size and simple hash of each file it finds. At the end, it tells you all the files that it suspects are actually duplicates.

I put the parts that were possibly reusable in src/lib.rs. Those are called from src/main.rs and tests/tests.rs. (I put tests.rs in its own directory because I needed to have some resources there to test with.)

In lib.rs, I put everything in a module like this:

pub mod file_digest {

In main.rs, I use mod and use to include it like this:

mod lib;
use filescan::file_digest::FileDigest;
use filescan::file_digest;

And that works pretty well, but I got a lot of complaints about unused code in src/lib.rs, so I had to add

#[allow(dead_code)],

which felt very icky.

The big problem, however, is that tests.rs doesn’t compile because I can’t figure out how to point it to the stuff it needs in lib.rs. Maybe I need to be smarter about Cargo.toml?

I put it on GitHub:

I’m really impressed with the language, but just as much with the community. People have been really helpful to me. Thanks!

Aaron

Short answer: Replace mod lib in main.rs (and mod ../src/lib in tests.rs) with

extern crate filescan;

Or, in fact, just delete these lines entirely, because extern crate filescan; is implied in 2018 edition.


Long answer:

Any cargo project can have:

  • At most one library, which is named after the project. (automatically assumed to be src/lib.rs if it exists)
  • Any number of binaries. (if src/main.rs exists, it is assumed to be a binary named after the project)
  • Any number of examples. (if not specified, assumed to be every .rs file in examples/)
  • Any number of integration tests. (if not specified, assumed to be every .rs file in tests/)

All of these are separate units of compilation, or crates. All of the binaries, examples, and integration tests can depend on the library as if it were one of your [dependencies].

When you wrote mod lib you ended up including the same source file src/lib.rs in multiple compilation units: both the library and your binary. Everything was fine when it built the library (because it’s all publically exported); but not all of it was used in the binary. Thus, warnings were generated when the compiler built the binary.

By using extern crate filescan instead, main simply depends on the library, and no spurious warnings are created.

That makes sense. Thank you for the thoughtful explanation.

I put your fix in my code, and it worked perfectly. Thank you so much.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.