Rust binary and library crates in one project
crate structure and code reuse.
a binary crate has main and produces an executable; a library crate has lib.rs and is reusable; put logic in the lib and a thin main that calls it.
duplicating core logic inside main.rs.
WHAT THIS TESTS Whether you understand Cargo's crate model and can design for reuse by separating a CLI shell from the logic it drives.
A GOOD ANSWER COVERS A crate is a compilation unit. A binary crate has a root file with a main function, usually src/main.rs, and compiles to a runnable executable. A library crate has src/lib.rs, has no main, and is built to be linked into other crates as a dependency, exposing a public API. A single Cargo package may contain both a library and one or more binaries. The idiomatic structure puts essentially all functionality in lib.rs and its modules, then makes main.rs a thin layer that parses arguments, sets up I/O, and calls into the library. This keeps the core importable by other projects and unit-testable without spawning a process, while the binary just wires the library to the command line.
COMMON WRONG ANSWERS Writing all logic directly in main.rs, which other crates cannot import and which is awkward to test. Believing a package can only be one or the other. Confusing crate with module. Exposing internal helpers in the public API unnecessarily.
LIKELY FOLLOW-UPS How do you declare multiple binaries with the bin directory. How does the library get its public API. How are integration tests structured against the lib. Difference between crate and package and module.
ONE CONCRETE EXAMPLE For a tool that lints config files, you create a package with src/lib.rs containing the parsing and validation logic exposed as public functions, and src/main.rs whose main reads command-line paths, calls the library's validate function, and prints results. The same lib.rs can be published to crates.io and depended on by a web service that validates uploads, with no change, because the logic never lived in main.rs.
Read the original → doc.rust-lang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.