Skip to content

Better explanation#1 #4749

@Linar46

Description

@Linar46

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions