Rust Book - Chapter 7.1
If you run rustc my_program.rs
, the Rust compiler considers the file you passed to be a crate [1]
@startuml
footer
Fig. 1 - Structure of a Rust crate.
end footer
scale 400 width
scale 300 height
[Crate] --> [Binary]
[Crate] --> [Library]
note left of Binary: programs that \ncan be compiled \nto an executable
note bottom of Library: no main function, \ncan't be compiled to an executable. \nDefines functionality \nintended to be shared with multiple programs
@enduml
We see from Fig. 1, that a crate can either a Library or a Binary crate.
A package can contain as many binary crates as you like, but at most only one library crate. A package must contain at least one crate, whether that's library or binary.
crate is used interchangeably with the concept of a library. When someone says crate, they usually mean library crate
@startuml
footer
Fig. 2 - Structure of a package
end footer
scale 400 width
scale 300 height
package "Package" {
[Cargo.toml]
[Crate1]
[Crate2]
[CrateN]
}
@enduml
What happens when we create a new package?
When we use cargo to create a new project, we see that it created a binary application
$cargo new my-project
Created binary (application) `my-project` package
~/projects/rust/the-book main ?14 >
Examining the content of Cargo.toml, we see that there's no mention of src/main.rs
. Why? This is because Cargo follows a convention that src/main.rs
is the crate root of a binary crate with the same name as the package. Cargo passes the crate root files to rustc to buld the binary.
Here, our package contains only 1 binary crate named my-project
. If a package contains src/main.rs and src/lib.rs, it has two crates: a binary and a library, both with the same name as the package. A package can have multiple binary crates by placing files in the src/bin directory: each file will be a separate binary crate.
[package]
name = "my-project"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
A crate is the smallest amount of code that the Rust compiler considers at a time. ↩︎