mirror of
https://github.com/learning-forge/marshal-rust.git
synced 2026-12-01 05:30:31 +00:00
docs(ch01): finalize Chapter 1 notes and idiomatic listings
- Rename package in 01-introduction-to-rust/Cargo.toml to ch01 - Update 01-introduction-to-rust/src/bin/listings.rs with i64 factorial and let-destructuring for Listing 1.2 - Merge NOTES.md into 01-introduction-to-rust/README.md, add Experiment 3 (i32 overflow), and update workspace clippy/fmt commands
This commit is contained in:
1 parent
564503c4c8
commit
33238fa959
3 files changed
+103
-26
No files matched your search
@@ -1,5 +1,5 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "ch01_intro_rust"
|
name = "ch01"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
|
|||||||
@@ -1,23 +1,23 @@
|
|||||||
# 1. Introduction to Rust
|
# 1. Introduction to Rust
|
||||||
|
|
||||||
> **Reference:** Donis Marshall, *Programming with Rust* (2024) — Chapter 1
|
> **Reference:** Donis Marshall, *Programming with Rust* (2024) — Chapter 1
|
||||||
> **Phase:** 1 (Basics & Tooling) | **Code:** [`mylib/src/listings.rs`](./mylib/src/listings.rs), [`mylib/src/lib.rs`](./mylib/src/lib.rs)
|
> **Phase:** 1 (Basics & Tooling) | **Code:** [`src/bin/listings.rs`](./src/bin/listings.rs)
|
||||||
|
|
||||||
## 1. Mental Model (My Own Words)
|
## 1. Mental Model (My Own Words)
|
||||||
|
|
||||||
- **Why Rust exists:** Memory and concurrency safety *without* a garbage collector. Instead of catching bugs at runtime (or via manual C/C++ discipline), Rust shifts those checks to compile time via the **borrow checker**.
|
- **Why Rust exists:** Memory and concurrency safety *without* a garbage collector. Instead of catching bugs at runtime (or via manual C/C++ discipline), Rust shifts those checks to compile time via the **borrow checker**.
|
||||||
- **Three paradigms combined:**
|
- **Three paradigms combined:**
|
||||||
- *Functional-light:* Functions are first-class values; immutability is the default to limit side effects.
|
- *Functional-light:* Functions as first-class citizens; immutability is the default to limit side effects.
|
||||||
- *Expression-oriented:* Blocks, `if`, and `match` return values rather than just mutating state (omit the trailing `;` to return).
|
- *Expression-oriented:* Blocks, `if`, and `match` return values rather than just mutating state.
|
||||||
- *Pattern-oriented:* `match` destructures tuples, enums, and structs—and the compiler enforces **exhaustiveness** (you must handle every case).
|
- *Pattern-oriented:* Rust treats **patterns** as a first-class way to bind and unpack data— not only in `match`, but anywhere values are bound (`let`, function parameters, `for` loops, `if let`, etc). The compiler uses known types to destructure tuples, structs, and enums, and enforces **exhaustiveness** whenever multiple cases are possible.
|
||||||
- **Safety pillars:** Single-owner principle (**Ownership**), temporary access (**Borrowing**), compile-time validity scopes (**Lifetimes**), RAII cleanup when values leave scope, and **zero-cost abstractions** (safety checks compile away, no runtime tax).
|
- **Safety pillars:** Single-owner principle (**Ownership**), temporary access (**Borrowing**), compile-time validity scopes (**Lifetimes**), Resource Acquisition Is Initialization (RAII), and **zero-cost abstractions** (safety checks compile away, no runtime tax).
|
||||||
- **Toolchain & unit map:**
|
- **Toolchain & unit map:**
|
||||||
- `rustup` (toolchain manager) → `cargo` (package/build manager, `Cargo.toml` manifest, `Cargo.lock` exact versions) → `rustc` (compiler) + `clippy` (linter) + `rustfmt` (formatter).
|
- `rustup` (toolchain manager in non-NixOS systems) → `cargo` (package/build manager, `Cargo.toml` manifest, `Cargo.lock` exact versions) → `rustc` (compiler) + `clippy` (linter) + `rustfmt` (formatter).
|
||||||
- **Module** (namespace) ⊂ **Crate** (compilation unit: binary or library) ⊂ **Package** (1+ crates sharing a `Cargo.toml`).
|
- **Module** (namespace) ⊂ **Crate** (compilation unit: binary or library) ⊂ **Package** (1+ crates sharing a `Cargo.toml`).
|
||||||
|
|
||||||
## 2. Break-It Experiments
|
## 2. Break-It Experiments
|
||||||
|
|
||||||
*Tested in [`mylib/src/listings.rs`](./mylib/src/listings.rs):*
|
*Tested in [`src/bin/listings.rs`](./src/bin/listings.rs):*
|
||||||
|
|
||||||
- **Experiment 1 (Trailing semicolon in an expression):** Add `;` after `1` or `n * factorial(n - 1)` inside `factorial`.
|
- **Experiment 1 (Trailing semicolon in an expression):** Add `;` after `1` or `n * factorial(n - 1)` inside `factorial`.
|
||||||
- **Result / `rustc` message:** Type mismatch—expected `i64`, found `()` (unit type), because `;` turns an expression into a statement.
|
- **Result / `rustc` message:** Type mismatch—expected `i64`, found `()` (unit type), because `;` turns an expression into a statement.
|
||||||
@@ -25,14 +25,89 @@
|
|||||||
- **Experiment 2 (Non-exhaustive `match`):** Remove the `_ => ...` arm in `factorial`.
|
- **Experiment 2 (Non-exhaustive `match`):** Remove the `_ => ...` arm in `factorial`.
|
||||||
- **Result / `rustc` message:** Compile error: `non-exhaustive patterns: i64::MIN..=-1_i64 and 2_i64..=i64::MAX not covered`.
|
- **Result / `rustc` message:** Compile error: `non-exhaustive patterns: i64::MIN..=-1_i64 and 2_i64..=i64::MAX not covered`.
|
||||||
- **Takeaway:** `match` won't compile if any possible input is unhandled.
|
- **Takeaway:** `match` won't compile if any possible input is unhandled.
|
||||||
|
- **Experiment 3 (Integer overflow with `i32`):** Run `factorial(n)` with `n >= 13` using the book's original `i32` signature.
|
||||||
|
- **Result / runtime message:** Panics in debug mode (`attempt to multiply with overflow`) because `13!` exceeds `i32::MAX` (`2,147,483,647`).
|
||||||
|
- **Takeaway:** Rust exposes explicit fixed-width numeric types (`i8`, `i16`, `i32`, `i64`, `i128`, etc.) so you can control the memory occupied by a value; switching `factorial` to `i64` supports larger results like `factorial(15)`.
|
||||||
|
|
||||||
## 3. Friction Log ("Gotchas")
|
## 3. Friction Log ("Gotchas")
|
||||||
|
|
||||||
- **Terminology trap — Crate vs. Package:** A "crate" is *not* a whole project; it's a single compilation unit (one binary or one library). A **package** is the `Cargo.toml` project that can contain multiple binary crates and at most one library crate.
|
- **Terminology trap — Crate vs. Package:** A "crate" is *not* a whole project; it's a single compilation unit (one binary or one library). A **package** is the `Cargo.toml` project that can contain multiple binary crates and at most one library crate.
|
||||||
- **File layout note:** `listings.rs` inside `mylib/src/` isn't compiled automatically unless declared as a module (`mod listings;`) in `lib.rs` or placed under `src/bin/`.
|
- **File layout note:** Arbitrary `.rs` files inside `src/` aren't compiled automatically unless declared as a module (`mod listings;`) in `lib.rs`/`main.rs`, or placed under `src/bin/` (which Cargo auto-discovers as binary targets).
|
||||||
|
|
||||||
## 4. Recall Prompts (Answer Without Looking)
|
## 4. Recall Prompts & Answers
|
||||||
|
|
||||||
1. What is the difference between a **statement** and an **expression** in Rust, and how does `;` change it?
|
1. **What is the difference between a statement and an expression in Rust, and how does `;` change it?**
|
||||||
2. How do **crate**, **package**, and **module** relate to each other?
|
|
||||||
3. What does the **borrow checker** enforce at compile time that garbage-collected languages handle at runtime (or not at all)?
|
Expressions evaluate to a resulting value, whereas statements are instructions that perform an action and never return a value. In Rust, adding a semicolon to an expression turns it into a statement, discarding its value.
|
||||||
|
|
||||||
|
2. **How do crate, package, and module relate to each other?**
|
||||||
|
|
||||||
|
A **crate** is the smallest compilation unit in Rust and can be either a binary or a library.
|
||||||
|
|
||||||
|
A **package** is a collection of crates that are built/published together (sharing a `Cargo.toml`). A **module** is a unit of organization in Rust that allows you to group related items together and control their visibility—similar to *namespaces* in other languages.
|
||||||
|
|
||||||
|
Interestingly, there is not a 1-to-1 mapping between `.rs` files and crates. In languages like C or C++, the compiler compiles each `.c`/`.cpp` file separately into object files and then links them together.
|
||||||
|
|
||||||
|
In a Rust application, `rustc` only looks at **one entry-point file** (the crate root). It completely ignores every other `.rs` file in the folder unless `src/main.rs` (or `src/lib.rs`) explicitly pulls it in using a `mod` declaration.
|
||||||
|
|
||||||
|
Imagine the following structure:
|
||||||
|
|
||||||
|
```plaintext
|
||||||
|
my_app/
|
||||||
|
├── Cargo.toml
|
||||||
|
└── src/
|
||||||
|
├── main.rs <-- Crate root (entry point)
|
||||||
|
├── config.rs
|
||||||
|
└── network/
|
||||||
|
├── mod.rs
|
||||||
|
└── client.rs
|
||||||
|
```
|
||||||
|
|
||||||
|
When `rustc` compiles `src/main.rs` (`rustc src/main.rs`):
|
||||||
|
- It sees `mod config;`, finds `src/config.rs`, and conceptually pastes its contents into a `config` namespace inside `main.rs`.
|
||||||
|
- It sees `mod network;`, finds `src/network/mod.rs`, and pastes it in.
|
||||||
|
- Inside `network`, it sees `mod client;`, finds `src/network/client.rs`, and pastes it inside `network`.
|
||||||
|
|
||||||
|
By the time `rustc` finishes reading the files, it has built a single in-memory **module tree** for that one crate, which it compiles together into a single binary executable (`my_app`). That's why the crate definition is scoped to a compilation unit rather than a `.rs` file or directory.
|
||||||
|
|
||||||
|
**Why this distinction matters:** Because the entire crate is compiled together, the compiler can perform **whole-program optimizations** that would be difficult or impossible in languages where code is compiled and linked in smaller pieces.
|
||||||
|
|
||||||
|
**When does a file become a separate crate?** A `.rs` file only becomes its own separate crate if Cargo treats it as a new root:
|
||||||
|
- `src/lib.rs` (your package's library crate)
|
||||||
|
- `src/main.rs` (your default binary crate)
|
||||||
|
- Any file placed inside `src/bin/` (e.g., `src/bin/worker.rs` compiles into a separate binary executable)
|
||||||
|
- Any file placed inside `examples/` (e.g., `examples/demo.rs` compiles into a standalone example executable, independent of your main binary)
|
||||||
|
- Integration tests in `tests/` or benchmarks in `benches/`
|
||||||
|
|
||||||
|
Everything else in `src/` is just a module belonging to whichever crate declares `mod` on it.
|
||||||
|
|
||||||
|
3. **What does the borrow checker enforce at compile time that garbage-collected languages handle at runtime (or not at all)?**
|
||||||
|
|
||||||
|
The borrow checker enforces ownership rules over memory at compile time, preventing **null pointer dereferences**, **data races**, and **use-after-free errors** before the program ever runs.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Repo Folder Convention
|
||||||
|
|
||||||
|
Treating the entire repo as a single crate would bloat a lot of unrelated code units into one giant crate and potentially make it difficult to manage and scale. Besides, many chapters return to similar examples which could result in name collisions, so I decided to split the repo into a package per chapter for easier management and navigation. Inside each chapter folder, there's a `Cargo.toml` that specifies the crate name and its dependencies, a `src/` folder with the source code (using `src/bin/` for runnable listings), and a `README.md` with notes and how to run the code.
|
||||||
|
|
||||||
|
Every package is self-contained, created with `cargo init --name <chapter_name>`, registered under `members` in the root [`Cargo.toml`](../Cargo.toml) workspace, and can be run independently via `cargo run -p <chapter_name> --bin <listing>`.
|
||||||
|
|
||||||
|
I'll keep this convention until I hit any issue that requires a change in structure.
|
||||||
|
|
||||||
|
## 6. Clippy and Best Practices from Day One
|
||||||
|
|
||||||
|
Although not enforced by the textbook, I decided to run `cargo clippy` at the end of each exercise to enforce best practices in Rust. This will help train my eye for idiomatic code and catch silly mistakes early. When `clippy` complains against canonical book entries (just like it happened with Listing 1.2), I will keep the canonical code as an inline comment and keep the idiomatic fix as the active executable code in the file. That feels like the best compromise to learn from the book's examples while also learning how to write idiomatic Rust.
|
||||||
|
|
||||||
|
The commands for checking everything in a package (or the whole workspace) are:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
# Single chapter package from the repo root:
|
||||||
|
cargo clippy -p <package_name> --all-targets -- -D warnings # must pass with 0 warnings
|
||||||
|
cargo fmt -p <package_name> -- --check # formatting check, must pass cleanly
|
||||||
|
|
||||||
|
# Or all chapters in the workspace at once:
|
||||||
|
cargo clippy --workspace --all-targets -- -D warnings
|
||||||
|
cargo fmt --all -- --check
|
||||||
|
```
|
||||||
|
The commitment on this repository is to manually run this before closing every chapter rather than relying on automated pre-commit hooks to build muscle memory. I'm open to revisiting this if the book starts presenting examples that challenge this approach.
|
||||||
@@ -1,23 +1,25 @@
|
|||||||
fn main(){
|
fn main() {
|
||||||
println!("{}",factorial(15));
|
println!("{}", factorial(15));
|
||||||
display_firstname(("Stark", "Tony"))
|
display_firstname(("Stark", "Tony"))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn factorial(n:i64) -> i64 {
|
fn factorial(n: i64) -> i64 {
|
||||||
// Code Listing 1.1. Factorial is a pure function and expression
|
// Code Listing 1.1. Factorial is a pure function and expression; adapted for 64-bit integers from 32-bit in the text.
|
||||||
match n {
|
match n {
|
||||||
0..=1=>1,
|
0..=1 => 1,
|
||||||
_=> n * factorial(n - 1)
|
_ => n * factorial(n - 1),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn display_firstname(name: (&str, &str)) {
|
||||||
|
|
||||||
fn display_firstname(name: (&str, &str)){
|
|
||||||
// Code listing 1.2. The display_firstname function displays a first name
|
// Code listing 1.2. The display_firstname function displays a first name
|
||||||
match name{
|
// Book uses:
|
||||||
(_, first) => println!("{}", first),
|
// match name{
|
||||||
|
// (_, first) => println!("{}", first),
|
||||||
|
// }
|
||||||
|
// but `let` is also pattern matching, and is idiomatic for a single irrefutable arm.
|
||||||
|
// adapting the listing after Clippy warning: "this match could be written as a `let` statement"
|
||||||
|
|
||||||
}
|
let (_, first) = name;
|
||||||
|
println!("{}", first);
|
||||||
}
|
}
|
||||||
|
|
||||||
Reference in new issue
Block a user