In Rust, a package can contain both a `src/main.rs` binary crate root and a `src/lib.rs` library crate root. Both crates will have the package name by default.
Structure of the Package
Typically, packages containing both a library and a binary crate will have just enough code in the binary crate to start an executable that calls code within the library crate. This allows other projects to benefit from the maximum functionality that the package provides, as the library crate’s code can be shared.
Rust
// src/main.rs
use my_package::my_function;
fn main() {
my_function();
}
In the example above, `my_function` is defined in the library crate and used in the binary crate.
Module Tree
The module tree should be defined in `src/lib.rs`. Then, any public items can be used in the binary crate by starting paths with the name of the package.
Rust
// src/main.rs
use my_package::my_function;
fn main() {
my_function();
}
In this example, `my_function` is a public function in the `my_module` module.
Public API
The binary crate becomes a user of the library crate just like a completely external crate would use the library crate: it can only use the public API. This helps you design a good API; not only are you the author, you’re also a client!
Rust
// src/main.rs
use my_package::my_function;
fn main() {
my_function();
}
In this example, `my_function` from `my_module` is used in the binary crate.