book icon indicating copy to clipboard operation
book copied to clipboard

Better explanation#1

Open Linar46 opened this issue 6 months ago • 0 comments

https://doc.rust-lang.org/stable/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html Think of these as layers of organization, from biggest to smallest:


1) Package (Cargo level)

A package is what Cargo manages.

  • Contains a Cargo.toml
  • Holds one or more crates
  • Used to build, test, and publish

Mental model: a project folder

my_project/        ← package
  Cargo.toml
  src/

2) Crate (compilation unit)

A crate is what the Rust compiler builds.

  • Either:

    • binary crate → executable (main.rs)
    • library crate → reusable code (lib.rs)
  • A package can contain:

    • 1 library crate
    • 0 or more binary crates

Mental model: a compiled program or library

src/main.rs   → binary crate
src/lib.rs    → library crate

3) Modules (code organization inside a crate)

Modules (mod) split a crate into smaller pieces.

  • Control structure and privacy
  • Can be nested

Mental model: folders/files inside the program

mod math {
    pub fn add(a: i32, b: i32) -> i32 {
        a + b
    }
}

You can also split into files:

src/
  main.rs
  math.rs

4) Paths (how you refer to things)

A path is how you name something.

  • Like a file path
  • Uses ::
math::add(2, 3)

Full paths can be long, so you use use:

use math::add;

add(2, 3);

How they fit together

Package (Cargo project)
└── Crate (compiled unit)
    └── Modules (code organization)
        └── Paths (how you refer to items)

Short analogy

  • Package → entire app/project
  • Crate → compiled program/library
  • Module → folders/files inside code
  • Path → file path to reach something

Minimal concrete example

my_project/
  Cargo.toml        ← package
  src/
    main.rs         ← crate root
    math.rs         ← module

main.rs

mod math;

use math::add;

fn main() {
    println!("{}", add(2, 3));
}

math.rs

pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

If one piece still feels unclear (usually “crate vs module”), specify and it can be narrowed further.

Linar46 avatar May 05 '26 17:05 Linar46