diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 0166328..0000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -name: Learning content or code issue -about: Report an error, unclear explanation, or propose a focused improvement -title: "" -labels: "" -assignees: "" ---- - -## What needs attention? - -Describe the incorrect behaviour, unclear explanation, or proposed addition. - -## Location - -Provide the module, file path, heading, or code example involved. - -## How to reproduce - -For a code problem, include the command you ran, the Rust version, and the -relevant compiler or program output. Remove secrets and unrelated machine -details. - -## Expected result - -Explain what you expected the code or documentation to say or do. - -## Suggested improvement - -If you have a proposed correction or teaching approach, describe it here. - -## Checklist - -- [ ] I searched existing issues and pull requests. -- [ ] This is not a security vulnerability (see `SECURITY.md`). -- [ ] I have identified whether the file is an intentionally broken exercise. diff --git a/.github/ISSUE_TEMPLATE/build-failure.yml b/.github/ISSUE_TEMPLATE/build-failure.yml new file mode 100644 index 0000000..060cd62 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/build-failure.yml @@ -0,0 +1,60 @@ +name: Build or validation failure +description: Report a command that fails unexpectedly for runnable repository material. +title: "[Build]: " +labels: ["bug"] +body: + - type: markdown + attributes: + value: "Share only information needed to reproduce the failure. Remove tokens, paths containing private information, and unrelated environment details." + - type: input + id: location + attributes: + label: Affected location + description: Provide the module, package, example, or exercise path. + placeholder: "06-intermediate-rust/traits_and_polymorphism" + validations: + required: true + - type: textarea + id: command + attributes: + label: Command run + description: Paste the exact command and the directory where you ran it. + placeholder: "From 06-intermediate-rust: make check" + validations: + required: true + - type: textarea + id: output + attributes: + label: Relevant output + description: Paste the smallest useful error output. Remove secrets and personal paths. + render: shell + validations: + required: true + - type: textarea + id: expected + attributes: + label: Expected behavior + description: Explain what you expected to compile, test, run, or validate. + validations: + required: true + - type: dropdown + id: exercise + attributes: + label: Is this an intentionally broken exercise? + options: + - "No" + - "Yes" + - "I am not sure" + validations: + required: true + - type: checkboxes + id: checks + attributes: + label: Checklist + options: + - label: I searched existing issues and pull requests. + required: true + - label: This is not a security vulnerability. + required: true + - label: I removed secrets and private machine details. + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..7ad4ca3 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: Security vulnerability + url: https://github.com/SaumilP/rust-learning-lab/security/policy + about: Please report security issues privately instead of opening a public issue. + - name: Contribution guidance + url: https://github.com/SaumilP/rust-learning-lab/blob/main/CONTRIBUTING.md + about: Read the content and validation guidance before proposing a larger change. diff --git a/.github/ISSUE_TEMPLATE/content-correction.yml b/.github/ISSUE_TEMPLATE/content-correction.yml new file mode 100644 index 0000000..2b05094 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/content-correction.yml @@ -0,0 +1,39 @@ +name: Content correction +description: Report an incorrect, unclear, or misleading explanation, example, or exercise. +title: "[Content]: " +labels: ["documentation"] +body: + - type: markdown + attributes: + value: "Thank you for helping improve the learning material. Do not include security vulnerabilities or personal information in a public issue." + - type: input + id: location + attributes: + label: Location + description: Provide the module, file path, heading, example, or exercise affected. + placeholder: "01-core-fundamentals/ownership/README.md — Moving values" + validations: + required: true + - type: textarea + id: problem + attributes: + label: What is inaccurate or unclear? + description: Explain the learner-facing problem and include a short quoted excerpt or code sample when useful. + validations: + required: true + - type: textarea + id: expected + attributes: + label: What should the material say or demonstrate instead? + description: Share a correction, counterexample, or teaching approach if you have one. + - type: checkboxes + id: checks + attributes: + label: Checklist + options: + - label: I searched existing issues and pull requests. + required: true + - label: This is not a security vulnerability. + required: true + - label: I checked whether the example is intentionally broken. + required: true diff --git a/.github/ISSUE_TEMPLATE/learning-proposal.yml b/.github/ISSUE_TEMPLATE/learning-proposal.yml new file mode 100644 index 0000000..e00fd32 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/learning-proposal.yml @@ -0,0 +1,46 @@ +name: Learning-path or content proposal +description: Suggest a focused lesson, exercise, project, or improvement to the learning sequence. +title: "[Proposal]: " +labels: ["enhancement"] +body: + - type: markdown + attributes: + value: "Proposals are most useful when they identify a learner problem and fit the existing curriculum rather than duplicating a current topic." + - type: textarea + id: learner-problem + attributes: + label: Learner problem + description: What would a learner struggle to understand, practice, or build without this change? + validations: + required: true + - type: input + id: location + attributes: + label: Proposed place in the learning path + description: Name the module or nearby topic where this work belongs. + placeholder: "After 02-standard-library/error_handling_basics" + validations: + required: true + - type: textarea + id: proposal + attributes: + label: Proposed material + description: Describe the lesson, example, exercise, project, or structural change. Link to related material if it exists. + validations: + required: true + - type: textarea + id: evidence + attributes: + label: Evidence or references + description: Share a concrete use case, learner feedback, documentation reference, or small example that supports the proposal. + - type: checkboxes + id: checks + attributes: + label: Checklist + options: + - label: I searched existing issues, pull requests, and nearby learning material. + required: true + - label: This proposal does not report a security vulnerability. + required: true + - label: I understand that new content needs clear objectives and validation evidence. + required: true diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..4e34be6 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,33 @@ +## Summary + +Describe the change in a few sentences. + +## Learner impact + +What will a learner or contributor understand, do, or find more easily after this change? + +## Scope and follow-up + +- [ ] This pull request is focused on one problem or improvement. +- [ ] I listed any deliberately deferred work below. + + + +## Validation + +List the commands you ran and their results. Include only relevant checks. + +```text + +``` + +## Content and metadata + +- [ ] This change does not affect topic metadata or content status. +- [ ] I updated affected `metadata.json` files and ran `contentctl validate`. +- [ ] I updated `CONTENT_STATUS.md` because the available evidence changed. +- [ ] I confirmed that intentionally broken exercises are still identified as such. + +## Review notes + +Point reviewers to the files, decisions, or learner-facing behavior that deserve particular attention. Do not include private planning notes, agent logs, credentials, or other sensitive information. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b72d207..0ac0475 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -86,3 +86,151 @@ jobs: - name: Run tests working-directory: ${{ matrix.path }} run: cargo test --all-targets + + advanced-host-projects: + name: Advanced ${{ matrix.path }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + path: + - 07-advanced-concepts/database_integration/01-sqlx-basics + - 07-advanced-concepts/modern_web_apis/02-axum-api + - 07-advanced-concepts/procedural_macros/01-derive-macro/example + - 07-advanced-concepts/procedural_macros/02-attribute-macro/example + - 07-advanced-concepts/procedural_macros/03-builder-pattern/example + - 07-advanced-concepts/performance_optimization/01-benchmarking + - 07-advanced-concepts/performance_optimization/03-simd-optimization + + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + + - name: Check formatting + working-directory: ${{ matrix.path }} + run: cargo fmt --all -- --check + + - name: Run Clippy + working-directory: ${{ matrix.path }} + run: cargo clippy --all-targets --all-features -- -D warnings + + - name: Run tests + working-directory: ${{ matrix.path }} + run: cargo test --all-targets + + advanced-wasm-projects: + name: WebAssembly ${{ matrix.path }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + path: + - 07-advanced-concepts/webassembly/01-hello-wasm + - 07-advanced-concepts/webassembly/04-game-of-life + + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + targets: wasm32-unknown-unknown + + - name: Check formatting + working-directory: ${{ matrix.path }} + run: cargo fmt --all -- --check + + - name: Run Clippy + working-directory: ${{ matrix.path }} + run: cargo clippy --target wasm32-unknown-unknown --all-targets --all-features -- -D warnings + + - name: Check WebAssembly project + working-directory: ${{ matrix.path }} + run: cargo check --target wasm32-unknown-unknown + + advanced-embedded-project: + name: Embedded STM32F401 blinky + runs-on: ubuntu-latest + + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + targets: thumbv7em-none-eabihf + + - name: Check formatting + working-directory: 07-advanced-concepts/embedded_rust/02-blinky + run: cargo fmt --all -- --check + + - name: Run Clippy + working-directory: 07-advanced-concepts/embedded_rust/02-blinky + run: cargo clippy --bin blinky -- -D warnings + + - name: Check embedded project + working-directory: 07-advanced-concepts/embedded_rust/02-blinky + run: cargo check + + markdown-links: + name: Internal Markdown links + runs-on: ubuntu-latest + + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Check local links + uses: lycheeverse/lychee-action@v2.9.0 + with: + args: --offline --root-dir . --no-progress './**/*.md' + failIfEmpty: true + + content-contracts: + name: Content contracts + runs-on: ubuntu-latest + + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + + - name: Check formatting + run: cargo fmt --manifest-path tools/contentctl/Cargo.toml --all -- --check + + - name: Run Clippy + run: cargo clippy --manifest-path tools/contentctl/Cargo.toml --all-targets --all-features -- -D warnings + + - name: Run tests + run: cargo test --manifest-path tools/contentctl/Cargo.toml --all-targets + + - name: Validate all topic metadata + run: cargo run --manifest-path tools/contentctl/Cargo.toml -- validate . + + - name: Validate quiz items + run: cargo run --manifest-path tools/contentctl/Cargo.toml -- validate-quiz challenges/quiz-items + + - name: Validate code review challenges + run: cargo run --manifest-path tools/contentctl/Cargo.toml -- validate-quiz challenges/code-review/items + + - name: Validate interview taxonomy + run: cargo run --manifest-path tools/contentctl/Cargo.toml -- validate-interview challenges/interview/taxonomy + + - name: Validate interview questions + run: cargo run --manifest-path tools/contentctl/Cargo.toml -- validate-interview-questions challenges/interview/questions challenges/interview/taxonomy + + - name: Validate compiler error labs + run: make -C labs/compiler-errors check diff --git a/.gitignore b/.gitignore index bbce6a6..f61fe2b 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,16 @@ build/ *.mmd *.dot +# Canonical content metadata and its validator lockfile +!schemas/*.schema.json +!docs/examples/topic-metadata.json +!**/metadata.json +!challenges/quiz-items/*.json +!challenges/code-review/items/*.json +!challenges/interview/taxonomy/*.json +!challenges/interview/questions/*.json +!tools/contentctl/Cargo.lock + # Internal project tracking files *IMPLEMENTATION_STATUS.md PHASE_*_COMPLETION_SUMMARY.md diff --git a/00-setup-and-basics/README.md b/00-setup-and-basics/README.md index 2925350..a70af67 100644 --- a/00-setup-and-basics/README.md +++ b/00-setup-and-basics/README.md @@ -25,7 +25,7 @@ Follow the sections in order: 3. Learn about variables in `variables_and_mutability/` 4. Explore types in `data_types/` 5. Master control flow in `control_flow/` -6. Practice with `exercises/` +6. Practice with [exercises/](exercises/) ## Quick Start @@ -64,4 +64,4 @@ Each subdirectory contains: - Read compiler errors carefully - they're helpful! - Use `cargo doc --open` to see documentation -Ready? Let's dive in! >€ +Ready? Let's dive in! diff --git a/00-setup-and-basics/control_flow/README.md b/00-setup-and-basics/control_flow/README.md new file mode 100644 index 0000000..8a38605 --- /dev/null +++ b/00-setup-and-basics/control_flow/README.md @@ -0,0 +1,20 @@ +# Control flow + +This example covers `if`, `loop`, `while`, `for`, `match`, `if let`, and `while let`. Rust control-flow constructs are expressions where it is useful for them to produce a value, and pattern matching must account for every possible case. + +Run it from this directory with `cargo run`. Change a branch condition, modify a range, or add a `match` arm to see how the compiler enforces the structure of the program. + +## What to notice + +- An `if` expression can produce a value when both branches have compatible types. +- `loop` can return a value through `break`. +- `for` works with iterators and is usually clearer than indexing a collection manually. +- `match` is exhaustive; a wildcard arm is one way to handle remaining cases. + +## Practice + +Use the [control-flow exercise](../exercises/03-control-flow/README.md) after running the example. + +## Next step + +Move to the [From-Zero curriculum](../../docs/curriculum/from-zero.md) for the recommended sequence after these foundations. diff --git a/00-setup-and-basics/control_flow/metadata.json b/00-setup-and-basics/control_flow/metadata.json new file mode 100644 index 0000000..f606721 --- /dev/null +++ b/00-setup-and-basics/control_flow/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"00-control-flow","title":"Control flow","status":"review","level":"beginner","estimated_minutes":35,"prerequisites":["00-data-types"],"concepts":["conditionals","loops","match","pattern-matching","if-let"],"tracks":["core"],"learning_objectives":["Use conditional expressions and loops to control a Rust program.","Write an exhaustive match expression and recognize when if let is appropriate."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"pending"}} diff --git a/00-setup-and-basics/data_types/README.md b/00-setup-and-basics/data_types/README.md new file mode 100644 index 0000000..0e87681 --- /dev/null +++ b/00-setup-and-basics/data_types/README.md @@ -0,0 +1,20 @@ +# Data types + +This example surveys scalar types, compound types, strings, conversions, aliases, and checked arithmetic. It is an orientation to the types you will encounter in early Rust programs, not a substitute for consulting the standard-library documentation when choosing an API. + +Run it from this directory with `cargo run`. Change a numeric literal, add a tuple element, or replace a checked addition with a wrapping addition to compare the behavior. + +## What to notice + +- Integer and floating-point literals can be inferred, but annotations make important boundaries explicit. +- Tuples can hold different types; arrays hold one type and have a fixed length. +- `String` owns growable text, while `&str` borrows a string slice. +- Checked arithmetic returns an `Option` instead of silently producing an out-of-range result. + +## Practice + +Use the [types exercise](../exercises/02-types/README.md) after running the example. + +## Next step + +Continue to [Control flow](../control_flow/README.md) to make decisions and repeat work with these values. diff --git a/00-setup-and-basics/data_types/metadata.json b/00-setup-and-basics/data_types/metadata.json new file mode 100644 index 0000000..25171f0 --- /dev/null +++ b/00-setup-and-basics/data_types/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"00-data-types","title":"Data types","status":"review","level":"beginner","estimated_minutes":35,"prerequisites":["00-variables-mutability"],"concepts":["scalar-types","compound-types","strings","type-conversion","checked-arithmetic"],"tracks":["core"],"learning_objectives":["Select basic scalar and compound types for a small Rust program.","Distinguish an owned String from a borrowed str slice.","Use checked arithmetic when overflow must be handled explicitly."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"pending"}} diff --git a/00-setup-and-basics/exercises/01-variables/README.md b/00-setup-and-basics/exercises/01-variables/README.md new file mode 100644 index 0000000..058155b --- /dev/null +++ b/00-setup-and-basics/exercises/01-variables/README.md @@ -0,0 +1,5 @@ +# Mutable running total + +Start with `starter.rs`. Make the program add `first` and `second`, store the result in a mutable binding, add 1, and print `8`. + +After attempting it, read the optional [solution notes](SOLUTION_NOTES.md). diff --git a/00-setup-and-basics/exercises/01-variables/SOLUTION_NOTES.md b/00-setup-and-basics/exercises/01-variables/SOLUTION_NOTES.md new file mode 100644 index 0000000..17c3476 --- /dev/null +++ b/00-setup-and-basics/exercises/01-variables/SOLUTION_NOTES.md @@ -0,0 +1,7 @@ +# Solution notes: mutable running total + +The first two bindings do not need `mut`: their values are assigned once and then only read. The total changes after it is created, so `let mut total` gives that specific binding permission to change. + +`first + second` is evaluated before the result is stored in `total`. The `+= 1` shorthand then updates that same binding. The final `println!` uses Rust's captured-identifier formatting, so `{total}` means “format the value named `total`.” + +If you reached `8` with a different expression, compare whether your version still makes the changing value explicit. Keeping the immutable inputs separate from the mutable result is usually easier to read and reason about. diff --git a/00-setup-and-basics/exercises/01-variables/solution.rs b/00-setup-and-basics/exercises/01-variables/solution.rs new file mode 100644 index 0000000..bcb2eac --- /dev/null +++ b/00-setup-and-basics/exercises/01-variables/solution.rs @@ -0,0 +1,7 @@ +fn main() { + let first = 3; + let second = 4; + let mut total = first + second; + total += 1; + println!("{total}"); +} diff --git a/00-setup-and-basics/exercises/01-variables/starter.rs b/00-setup-and-basics/exercises/01-variables/starter.rs new file mode 100644 index 0000000..7186a47 --- /dev/null +++ b/00-setup-and-basics/exercises/01-variables/starter.rs @@ -0,0 +1,7 @@ +fn main() { + let first = 3; + let second = 4; + let total = first + second; + total += 1; + println!("{total}"); +} diff --git a/00-setup-and-basics/exercises/02-types/README.md b/00-setup-and-basics/exercises/02-types/README.md new file mode 100644 index 0000000..53dbbd8 --- /dev/null +++ b/00-setup-and-basics/exercises/02-types/README.md @@ -0,0 +1,5 @@ +# Convert a temperature + +Start with `starter.rs`. Complete `to_celsius` so it converts 68 degrees Fahrenheit to 20 degrees Celsius using floating-point arithmetic. + +After attempting it, read the optional [solution notes](SOLUTION_NOTES.md). diff --git a/00-setup-and-basics/exercises/02-types/SOLUTION_NOTES.md b/00-setup-and-basics/exercises/02-types/SOLUTION_NOTES.md new file mode 100644 index 0000000..2695c29 --- /dev/null +++ b/00-setup-and-basics/exercises/02-types/SOLUTION_NOTES.md @@ -0,0 +1,7 @@ +# Solution notes: convert a temperature + +The formula is `(fahrenheit - 32) * 5 / 9`. This solution writes the constants as `32.0`, `5.0`, and `9.0` so the whole calculation uses `f64` floating-point values rather than integer arithmetic. + +The function signature documents both sides of the conversion: it accepts an `f64` and returns an `f64`. That lets the caller reuse the conversion instead of tying it to one printed example. + +`println!("{:.1}", ...)` displays one decimal place, which makes the expected output `20.0`. Formatting affects how the result is shown; it does not change the value returned by `to_celsius`. diff --git a/00-setup-and-basics/exercises/02-types/solution.rs b/00-setup-and-basics/exercises/02-types/solution.rs new file mode 100644 index 0000000..c4161f7 --- /dev/null +++ b/00-setup-and-basics/exercises/02-types/solution.rs @@ -0,0 +1,7 @@ +fn to_celsius(fahrenheit: f64) -> f64 { + (fahrenheit - 32.0) * 5.0 / 9.0 +} + +fn main() { + println!("{:.1}", to_celsius(68.0)); +} diff --git a/00-setup-and-basics/exercises/02-types/starter.rs b/00-setup-and-basics/exercises/02-types/starter.rs new file mode 100644 index 0000000..1f201b2 --- /dev/null +++ b/00-setup-and-basics/exercises/02-types/starter.rs @@ -0,0 +1,7 @@ +fn to_celsius(fahrenheit: f64) -> f64 { + todo!() +} + +fn main() { + println!("{:.1}", to_celsius(68.0)); +} diff --git a/00-setup-and-basics/exercises/03-control-flow/README.md b/00-setup-and-basics/exercises/03-control-flow/README.md new file mode 100644 index 0000000..ea076f6 --- /dev/null +++ b/00-setup-and-basics/exercises/03-control-flow/README.md @@ -0,0 +1,5 @@ +# Classify a number + +Start with `starter.rs`. Use an `if` expression to return `"negative"`, `"zero"`, or `"positive"` for the supplied integer. + +After attempting it, read the optional [solution notes](SOLUTION_NOTES.md). diff --git a/00-setup-and-basics/exercises/03-control-flow/SOLUTION_NOTES.md b/00-setup-and-basics/exercises/03-control-flow/SOLUTION_NOTES.md new file mode 100644 index 0000000..3d5c790 --- /dev/null +++ b/00-setup-and-basics/exercises/03-control-flow/SOLUTION_NOTES.md @@ -0,0 +1,7 @@ +# Solution notes: classify a number + +An `if` in Rust is an expression, so each branch can produce the string returned by `classify`. The branches are ordered from negative to zero to the remaining case; after the first two checks fail, the number must be positive. + +The return type is `&'static str` because every branch returns a string literal. Those literals are embedded in the program and remain available for the whole execution, so the function can return a reference to one without allocating a new `String`. + +This is also a useful place to distinguish `=` from `==`: `number == 0` compares two values, while `=` would assign a value and is not the condition this function needs. diff --git a/00-setup-and-basics/exercises/03-control-flow/solution.rs b/00-setup-and-basics/exercises/03-control-flow/solution.rs new file mode 100644 index 0000000..4224705 --- /dev/null +++ b/00-setup-and-basics/exercises/03-control-flow/solution.rs @@ -0,0 +1,7 @@ +fn classify(number: i32) -> &'static str { + if number < 0 { "negative" } else if number == 0 { "zero" } else { "positive" } +} + +fn main() { + println!("{}", classify(-2)); +} diff --git a/00-setup-and-basics/exercises/03-control-flow/starter.rs b/00-setup-and-basics/exercises/03-control-flow/starter.rs new file mode 100644 index 0000000..48e93ea --- /dev/null +++ b/00-setup-and-basics/exercises/03-control-flow/starter.rs @@ -0,0 +1,7 @@ +fn classify(number: i32) -> &'static str { + todo!() +} + +fn main() { + println!("{}", classify(-2)); +} diff --git a/00-setup-and-basics/exercises/04-functions/README.md b/00-setup-and-basics/exercises/04-functions/README.md new file mode 100644 index 0000000..0075c50 --- /dev/null +++ b/00-setup-and-basics/exercises/04-functions/README.md @@ -0,0 +1,5 @@ +# Return the larger value + +Start with `starter.rs`. Implement `larger` without printing inside the function. The final expression should return the selected value. + +After attempting it, read the optional [solution notes](SOLUTION_NOTES.md). diff --git a/00-setup-and-basics/exercises/04-functions/SOLUTION_NOTES.md b/00-setup-and-basics/exercises/04-functions/SOLUTION_NOTES.md new file mode 100644 index 0000000..65c8c70 --- /dev/null +++ b/00-setup-and-basics/exercises/04-functions/SOLUTION_NOTES.md @@ -0,0 +1,7 @@ +# Solution notes: return the larger value + +The `if` expression is the final expression in `larger`, so its selected branch becomes the function's return value. No `return` keyword or trailing semicolon is needed here. + +When `left` is greater than `right`, the first branch produces `left`; otherwise the second branch produces `right`. For equal inputs, this implementation returns `right`, but the numeric result is the same either way. + +Keeping `println!` in `main` separates calculation from presentation. That makes `larger` easier to test and reuse in code that needs the value without writing to the terminal. diff --git a/00-setup-and-basics/exercises/04-functions/solution.rs b/00-setup-and-basics/exercises/04-functions/solution.rs new file mode 100644 index 0000000..ab32b33 --- /dev/null +++ b/00-setup-and-basics/exercises/04-functions/solution.rs @@ -0,0 +1,7 @@ +fn larger(left: i32, right: i32) -> i32 { + if left > right { left } else { right } +} + +fn main() { + println!("{}", larger(9, 4)); +} diff --git a/00-setup-and-basics/exercises/04-functions/starter.rs b/00-setup-and-basics/exercises/04-functions/starter.rs new file mode 100644 index 0000000..e3feb3b --- /dev/null +++ b/00-setup-and-basics/exercises/04-functions/starter.rs @@ -0,0 +1,7 @@ +fn larger(left: i32, right: i32) -> i32 { + todo!() +} + +fn main() { + println!("{}", larger(9, 4)); +} diff --git a/00-setup-and-basics/exercises/README.md b/00-setup-and-basics/exercises/README.md new file mode 100644 index 0000000..7459120 --- /dev/null +++ b/00-setup-and-basics/exercises/README.md @@ -0,0 +1,5 @@ +# Setup and basics exercises + +Attempt these in order after the corresponding Module 00 lesson. Each folder includes a starter file and a solution file; read the prompt, copy the starter into a scratch project or run it with `rustc`, and open the solution only after you have made a serious attempt. + +The solutions are reference implementations, not the only valid answers. Compare the behaviour and explain any difference between your approach and the reference. diff --git a/00-setup-and-basics/hello_world/README.md b/00-setup-and-basics/hello_world/README.md new file mode 100644 index 0000000..01f1406 --- /dev/null +++ b/00-setup-and-basics/hello_world/README.md @@ -0,0 +1,15 @@ +# Hello, world! + +This first program introduces the shape of a Rust binary: the `main` function, the `println!` macro, variables, and formatting values in output. + +Run it from this directory with `cargo run`. Then change the `audience`, `language`, or `numbers` values and run it again to see how Rust formats each value. + +## What to notice + +- Every executable Rust program starts at `fn main()`. +- `println!` is a macro, which is why its name ends with `!`. +- `{}` formats a value for display, while `{:?}` shows its debug representation. + +## Next step + +Continue to [Variables and mutability](../variables_and_mutability/README.md) to see how bindings work after a program has values to print. diff --git a/00-setup-and-basics/hello_world/metadata.json b/00-setup-and-basics/hello_world/metadata.json new file mode 100644 index 0000000..02baa96 --- /dev/null +++ b/00-setup-and-basics/hello_world/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"00-hello-world","title":"Hello, world!","status":"review","level":"beginner","estimated_minutes":15,"prerequisites":[],"concepts":["rust-binary","main-function","println-macro","formatting"],"tracks":["core"],"learning_objectives":["Run a Rust binary and explain the role of its main function.","Use println! placeholders to display values."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"pending"}} diff --git a/00-setup-and-basics/variables_and_mutability/README.md b/00-setup-and-basics/variables_and_mutability/README.md new file mode 100644 index 0000000..fe6669a --- /dev/null +++ b/00-setup-and-basics/variables_and_mutability/README.md @@ -0,0 +1,20 @@ +# Variables and mutability + +Rust bindings are immutable unless they are declared with `mut`. The example also demonstrates constants, shadowing, scope, type inference, and destructuring. + +Run it from this directory with `cargo run`. Uncomment one intentionally invalid assignment at a time if you want to read the compiler's explanation, then restore it before continuing. + +## What to notice + +- `let value = ...` creates an immutable binding by default. +- `let mut value = ...` permits reassignment, but it does not permit changing the binding's type. +- Shadowing creates a new binding, so the later binding may have a different type. +- A binding is dropped when its scope ends. + +## Practice + +Use the [variables exercise](../exercises/01-variables/README.md) after running the example. + +## Next step + +Continue to [Data types](../data_types/README.md) to choose types for the values a binding holds. diff --git a/00-setup-and-basics/variables_and_mutability/metadata.json b/00-setup-and-basics/variables_and_mutability/metadata.json new file mode 100644 index 0000000..197defc --- /dev/null +++ b/00-setup-and-basics/variables_and_mutability/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"00-variables-mutability","title":"Variables and mutability","status":"review","level":"beginner","estimated_minutes":30,"prerequisites":["00-hello-world"],"concepts":["bindings","mutability","constants","shadowing","scope","type-inference"],"tracks":["core"],"learning_objectives":["Choose between an immutable binding, a mutable binding, a constant, and shadowing.","Explain how a binding's scope affects when its value is dropped."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"pending"}} diff --git a/01-core-fundamentals/README.md b/01-core-fundamentals/README.md index 5c8990f..ea72066 100644 --- a/01-core-fundamentals/README.md +++ b/01-core-fundamentals/README.md @@ -251,10 +251,10 @@ loop { break; } ## Module Status --  Structure established -- ó Concept documentation in progress -- ó Code examples needed -- ó Exercises pending +- Complete — Structure established +- In progress — Concept documentation in progress +- In progress — Code examples needed +- In progress — Exercises pending ## Next Steps diff --git a/01-core-fundamentals/control_flow/metadata.json b/01-core-fundamentals/control_flow/metadata.json new file mode 100644 index 0000000..483e309 --- /dev/null +++ b/01-core-fundamentals/control_flow/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"01-control-flow","title":"Control flow","status":"review","level":"beginner","estimated_minutes":35,"prerequisites":["01-variables-mutability"],"concepts":["conditionals","loops","match"],"tracks":["core"],"learning_objectives":["Choose appropriate conditional, loop, and match expressions."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"pending"}} diff --git a/01-core-fundamentals/data_types/metadata.json b/01-core-fundamentals/data_types/metadata.json new file mode 100644 index 0000000..97b7c90 --- /dev/null +++ b/01-core-fundamentals/data_types/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"01-data-types","title":"Data types","status":"review","level":"beginner","estimated_minutes":30,"prerequisites":["01-variables-mutability"],"concepts":["scalars","compound-types","type-inference"],"tracks":["core"],"learning_objectives":["Select Rust data types for common values."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"pending"}} diff --git a/01-core-fundamentals/error_handling/metadata.json b/01-core-fundamentals/error_handling/metadata.json new file mode 100644 index 0000000..be77df5 --- /dev/null +++ b/01-core-fundamentals/error_handling/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"01-error-handling","title":"Error handling","status":"review","level":"beginner","estimated_minutes":35,"prerequisites":["01-control-flow"],"concepts":["option","result","recoverable-errors"],"tracks":["core"],"learning_objectives":["Choose explicit representations for absent values and recoverable failures."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"pending"}} diff --git a/01-core-fundamentals/functions/metadata.json b/01-core-fundamentals/functions/metadata.json new file mode 100644 index 0000000..d66afe9 --- /dev/null +++ b/01-core-fundamentals/functions/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"01-functions","title":"Functions","status":"review","level":"beginner","estimated_minutes":30,"prerequisites":["01-variables-mutability"],"concepts":["parameters","return-values","expressions"],"tracks":["core"],"learning_objectives":["Write functions with clear inputs and return values."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"pending"}} diff --git a/01-core-fundamentals/ownership/metadata.json b/01-core-fundamentals/ownership/metadata.json new file mode 100644 index 0000000..24520c2 --- /dev/null +++ b/01-core-fundamentals/ownership/metadata.json @@ -0,0 +1,27 @@ +{ + "$schema": "../../schemas/topic-metadata-v1.schema.json", + "schema_version": 1, + "id": "01-ownership", + "title": "Ownership", + "status": "review", + "level": "intermediate", + "estimated_minutes": 120, + "prerequisites": ["01-variables-mutability", "01-functions"], + "concepts": ["ownership", "move-semantics", "copy-types", "drop"], + "tracks": ["core", "java", "python", "cpp", "go"], + "learning_objectives": [ + "State Rust's ownership rules.", + "Predict when assignment or a function call moves a value.", + "Distinguish Copy values from moved values.", + "Choose when a function should take or return ownership." + ], + "website": { + "published": false, + "order": null + }, + "validation": { + "content_rubric": "pending", + "examples": "passed", + "exercises": "pending" + } +} diff --git a/01-core-fundamentals/variables_and_mutability/metadata.json b/01-core-fundamentals/variables_and_mutability/metadata.json new file mode 100644 index 0000000..4321d96 --- /dev/null +++ b/01-core-fundamentals/variables_and_mutability/metadata.json @@ -0,0 +1,27 @@ +{ + "$schema": "../../schemas/topic-metadata-v1.schema.json", + "schema_version": 1, + "id": "01-variables-mutability", + "title": "Variables and Mutability", + "status": "review", + "level": "beginner", + "estimated_minutes": 90, + "prerequisites": [], + "concepts": ["variables", "immutability", "mutability", "shadowing", "constants"], + "tracks": ["core", "java", "python", "cpp", "go"], + "learning_objectives": [ + "Declare immutable and mutable variable bindings.", + "Explain why Rust makes bindings immutable by default.", + "Distinguish shadowing from mutation.", + "Choose between a variable and a constant." + ], + "website": { + "published": false, + "order": null + }, + "validation": { + "content_rubric": "pending", + "examples": "passed", + "exercises": "pending" + } +} diff --git a/02-standard-library/README.md b/02-standard-library/README.md index 6d55d9d..ae24012 100644 --- a/02-standard-library/README.md +++ b/02-standard-library/README.md @@ -270,10 +270,10 @@ match result { ## Module Status --  Structure established -- ó Concept documentation in progress -- ó Code examples needed -- ó Exercises pending +- Complete — Structure established +- In progress — Concept documentation in progress +- In progress — Code examples needed +- In progress — Exercises pending ## Next Steps diff --git a/02-standard-library/collections/metadata.json b/02-standard-library/collections/metadata.json new file mode 100644 index 0000000..8746fbc --- /dev/null +++ b/02-standard-library/collections/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"02-collections","title":"Collections","status":"review","level":"beginner","estimated_minutes":45,"prerequisites":["01-data-types"],"concepts":["vectors","hash-maps","collection-choices"],"tracks":["core"],"learning_objectives":["Choose and use standard collections for common data shapes."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"pending"}} diff --git a/02-standard-library/common_traits/metadata.json b/02-standard-library/common_traits/metadata.json new file mode 100644 index 0000000..8f08afb --- /dev/null +++ b/02-standard-library/common_traits/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"02-common-traits","title":"Common traits","status":"review","level":"intermediate","estimated_minutes":35,"prerequisites":["01-data-types"],"concepts":["debug","clone","partial-eq"],"tracks":["core"],"learning_objectives":["Recognize common trait contracts and their derived implementations."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"pending"}} diff --git a/02-standard-library/error_handling_basics/metadata.json b/02-standard-library/error_handling_basics/metadata.json new file mode 100644 index 0000000..3ae0e34 --- /dev/null +++ b/02-standard-library/error_handling_basics/metadata.json @@ -0,0 +1,27 @@ +{ + "$schema": "../../schemas/topic-metadata-v1.schema.json", + "schema_version": 1, + "id": "02-result", + "title": "Result and Recoverable Errors", + "status": "review", + "level": "intermediate", + "estimated_minutes": 120, + "prerequisites": ["01-control-flow"], + "concepts": ["result", "option", "error-propagation", "question-mark-operator", "custom-errors"], + "tracks": ["core", "java", "python", "cpp", "go"], + "learning_objectives": [ + "Choose between Option and Result for an operation's outcome.", + "Handle Result values with pattern matching and combinators.", + "Propagate compatible errors with the question-mark operator.", + "Distinguish recoverable errors from conditions that justify a panic." + ], + "website": { + "published": false, + "order": null + }, + "validation": { + "content_rubric": "pending", + "examples": "passed", + "exercises": "pending" + } +} diff --git a/02-standard-library/iterator_patterns/metadata.json b/02-standard-library/iterator_patterns/metadata.json new file mode 100644 index 0000000..92690a4 --- /dev/null +++ b/02-standard-library/iterator_patterns/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"02-iterator-patterns","title":"Iterator patterns","status":"review","level":"intermediate","estimated_minutes":45,"prerequisites":["02-collections"],"concepts":["iterators","map","filter"],"tracks":["core"],"learning_objectives":["Transform and collect data with iterator adaptors."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"pending"}} diff --git a/02-standard-library/string_operations/metadata.json b/02-standard-library/string_operations/metadata.json new file mode 100644 index 0000000..b61fbf3 --- /dev/null +++ b/02-standard-library/string_operations/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"02-string-operations","title":"String operations","status":"review","level":"beginner","estimated_minutes":40,"prerequisites":["01-ownership"],"concepts":["string","string-slices","utf8"],"tracks":["core"],"learning_objectives":["Manipulate UTF-8 text without assuming byte indexing."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"pending"}} diff --git a/03-tooling-and-quality/README.md b/03-tooling-and-quality/README.md index 970a177..e6a483e 100644 --- a/03-tooling-and-quality/README.md +++ b/03-tooling-and-quality/README.md @@ -263,10 +263,10 @@ println!("x = {}", x); ## Module Status --  Structure established -- ó Concept documentation in progress -- ó Code examples needed -- ó Exercises pending +- Complete — Structure established +- In progress — Concept documentation in progress +- In progress — Code examples needed +- In progress — Exercises pending ## Next Steps diff --git a/03-tooling-and-quality/code_quality_tools/metadata.json b/03-tooling-and-quality/code_quality_tools/metadata.json new file mode 100644 index 0000000..5ada4be --- /dev/null +++ b/03-tooling-and-quality/code_quality_tools/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"03-code-quality-tools","title":"Code quality tools","status":"review","level":"beginner","estimated_minutes":30,"prerequisites":["01-functions"],"concepts":["rustfmt","clippy","linting"],"tracks":["core"],"learning_objectives":["Use formatting and linting feedback in a Rust workflow."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"not_applicable"}} diff --git a/03-tooling-and-quality/debugging/metadata.json b/03-tooling-and-quality/debugging/metadata.json new file mode 100644 index 0000000..e54a2ba --- /dev/null +++ b/03-tooling-and-quality/debugging/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"03-debugging","title":"Debugging","status":"review","level":"beginner","estimated_minutes":35,"prerequisites":["01-control-flow"],"concepts":["compiler-errors","debugging","diagnostics"],"tracks":["core"],"learning_objectives":["Use compiler diagnostics and focused experiments to debug Rust."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"not_applicable"}} diff --git a/03-tooling-and-quality/documentation/metadata.json b/03-tooling-and-quality/documentation/metadata.json new file mode 100644 index 0000000..aa03408 --- /dev/null +++ b/03-tooling-and-quality/documentation/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"03-documentation","title":"Documentation","status":"review","level":"beginner","estimated_minutes":25,"prerequisites":["01-functions"],"concepts":["rustdoc","api-documentation","examples"],"tracks":["core"],"learning_objectives":["Document public Rust APIs with useful examples."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"not_applicable"}} diff --git a/03-tooling-and-quality/testing/metadata.json b/03-tooling-and-quality/testing/metadata.json new file mode 100644 index 0000000..e1a5d95 --- /dev/null +++ b/03-tooling-and-quality/testing/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"03-testing","title":"Testing","status":"review","level":"beginner","estimated_minutes":45,"prerequisites":["01-functions"],"concepts":["unit-tests","integration-tests","assertions"],"tracks":["core"],"learning_objectives":["Write and run focused Rust tests."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"pending"}} diff --git a/06-advanced-functions/README.md b/06-advanced-functions/README.md deleted file mode 100644 index e3be7ea..0000000 --- a/06-advanced-functions/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# Advanced Function and Type-System Review - -This supplementary module revisits ownership, generics, traits, and enum-based -design in a compact form. It is useful as a review after -[`01-core-fundamentals`](../01-core-fundamentals/) and -[`02-standard-library`](../02-standard-library/). - -For the main intermediate sequence—including modules, concurrency, async, -testing, and macros—continue with -[`06-intermediate-rust`](../06-intermediate-rust/). - -Each topic contains a concept README and key takeaways. Read those notes, write -a small example from memory, and then compare it with the related material in -the main learning path. diff --git a/06-intermediate-rust/Makefile b/06-intermediate-rust/Makefile index cfe5f74..c1d81d6 100644 --- a/06-intermediate-rust/Makefile +++ b/06-intermediate-rust/Makefile @@ -7,7 +7,9 @@ RUSTFMT ?= rustfmt BUILD_DIR ?= build RUST_EDITION ?= 2021 -EXAMPLE_SOURCES := $(shell find . -type f -path '*/examples/*.rs' | sort) +# Supplementary review examples are Draft material and are intentionally outside +# the canonical module checks until their own validation is added. +EXAMPLE_SOURCES := $(shell find . -type f -path '*/examples/*.rs' ! -path './supplementary/*' | sort) EXAMPLE_BINS := $(patsubst ./%.rs,$(BUILD_DIR)/%,$(EXAMPLE_SOURCES)) .DEFAULT_GOAL := help diff --git a/06-intermediate-rust/README.md b/06-intermediate-rust/README.md index d1c6069..bdb5016 100644 --- a/06-intermediate-rust/README.md +++ b/06-intermediate-rust/README.md @@ -1,7 +1,6 @@ # Module 06: Intermediate Rust -This module connects Rust's basic syntax to the type-system tools used in real -applications. Work through the concepts in order: +This module connects Rust's basic syntax to the type-system tools used in real applications. Work through the concepts in order: 1. [Ownership and borrowing](ownership_and_borrowing/README.md) 2. [Traits and polymorphism](traits_and_polymorphism/README.md) @@ -9,10 +8,7 @@ applications. Work through the concepts in order: 4. [Enums and pattern matching](enums_and_pattern_matching/README.md) 5. [Lifetimes](lifetimes/README.md) -Each concept contains a short explanation, a runnable example, and a compact -`key_takeaways.md`. The `exercises/` directory contains deliberately broken -programs; read the problem first, attempt a repair, and consult hints only when -needed. +Each concept contains a short explanation, a runnable example, and a compact `key_takeaways.md`. The `exercises/` directory contains deliberately broken programs; read the problem first, attempt a repair, and consult hints only when needed. ## Commands @@ -27,8 +23,10 @@ make check make clean ``` -Generated binaries and documentation live under `build/`. They are disposable -and can always be recreated with `make build` or `make docs`. +Generated binaries and documentation live under `build/`. They are disposable and can always be recreated with `make build` or `make docs`. -Prerequisites: modules 01–03. Continue with module 07 after completing all four -exercises. +Prerequisites: modules 01–03. Continue with module 07 after completing all four exercises. + +## Supplementary review + +The optional [supplementary review](supplementary/README.md) contains longer examples and extra exercises for ownership, traits, generics, and enums. Complete the primary sequence first; this material is not part of the canonical `make check` coverage while it remains Draft. diff --git a/06-intermediate-rust/enums_and_pattern_matching/metadata.json b/06-intermediate-rust/enums_and_pattern_matching/metadata.json new file mode 100644 index 0000000..280f894 --- /dev/null +++ b/06-intermediate-rust/enums_and_pattern_matching/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"06-enums-pattern-matching","title":"Enums and pattern matching","status":"review","level":"intermediate","estimated_minutes":45,"prerequisites":["01-control-flow"],"concepts":["enums","patterns","exhaustiveness"],"tracks":["core"],"learning_objectives":["Model states with enums and handle them exhaustively."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"pending"}} diff --git a/06-intermediate-rust/generics/metadata.json b/06-intermediate-rust/generics/metadata.json new file mode 100644 index 0000000..344e304 --- /dev/null +++ b/06-intermediate-rust/generics/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"06-generics","title":"Generics","status":"review","level":"intermediate","estimated_minutes":40,"prerequisites":["01-functions"],"concepts":["generics","type-parameters","trait-bounds"],"tracks":["core"],"learning_objectives":["Use generic parameters and bounds to express reusable APIs."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"pending"}} diff --git a/06-intermediate-rust/lifetimes/metadata.json b/06-intermediate-rust/lifetimes/metadata.json new file mode 100644 index 0000000..dafca7e --- /dev/null +++ b/06-intermediate-rust/lifetimes/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"06-lifetimes","title":"Lifetimes","status":"review","level":"intermediate","estimated_minutes":50,"prerequisites":["01-ownership"],"concepts":["lifetimes","references","borrowing"],"tracks":["core"],"learning_objectives":["Explain and annotate relationships between borrowed values."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"pending"}} diff --git a/06-intermediate-rust/ownership_and_borrowing/metadata.json b/06-intermediate-rust/ownership_and_borrowing/metadata.json new file mode 100644 index 0000000..9d65a25 --- /dev/null +++ b/06-intermediate-rust/ownership_and_borrowing/metadata.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"06-ownership-borrowing","title":"Ownership and borrowing","status":"review","level":"intermediate","estimated_minutes":45,"prerequisites":["01-ownership"],"concepts":["ownership","borrowing","references"],"tracks":["core"],"learning_objectives":["Apply ownership and borrowing rules when designing APIs."],"website":{"published":false,"order":null},"validation":{"content_rubric":"pending","examples":"passed","exercises":"pending"}} diff --git a/06-intermediate-rust/supplementary/README.md b/06-intermediate-rust/supplementary/README.md new file mode 100644 index 0000000..fdb9aa1 --- /dev/null +++ b/06-intermediate-rust/supplementary/README.md @@ -0,0 +1,11 @@ +# Supplementary Module 06 Review + +These optional deep dives revisit the main Module 06 concepts with larger examples. They are useful after the primary sequence, not as a replacement for it. + +1. [Ownership and borrowing](ownership_and_borrowing/README.md) explores string manipulation. +2. [Traits and polymorphism](traits_and_polymorphism/README.md) builds a logger system. +3. [Generics](generics/README.md) develops reusable container operations. +4. [Enums and pattern matching](enums_and_pattern_matching/README.md) models a small JSON value tree. +5. [Exercises](exercises/) provides four additional review problems. + +This material remains Draft and is intentionally excluded from the primary Module 06 `make check` target until it has its own validation coverage. diff --git a/06-advanced-functions/enums_and_pattern_matching/README.md b/06-intermediate-rust/supplementary/enums_and_pattern_matching/README.md similarity index 100% rename from 06-advanced-functions/enums_and_pattern_matching/README.md rename to 06-intermediate-rust/supplementary/enums_and_pattern_matching/README.md diff --git a/06-advanced-functions/enums_and_pattern_matching/examples/json_parser.rs b/06-intermediate-rust/supplementary/enums_and_pattern_matching/examples/json_parser.rs similarity index 100% rename from 06-advanced-functions/enums_and_pattern_matching/examples/json_parser.rs rename to 06-intermediate-rust/supplementary/enums_and_pattern_matching/examples/json_parser.rs diff --git a/06-advanced-functions/enums_and_pattern_matching/key_takeaways.md b/06-intermediate-rust/supplementary/enums_and_pattern_matching/key_takeaways.md similarity index 100% rename from 06-advanced-functions/enums_and_pattern_matching/key_takeaways.md rename to 06-intermediate-rust/supplementary/enums_and_pattern_matching/key_takeaways.md diff --git a/06-advanced-functions/exercises/exercise_1_string_processor/broken_code.rs b/06-intermediate-rust/supplementary/exercises/exercise_1_string_processor/broken_code.rs similarity index 100% rename from 06-advanced-functions/exercises/exercise_1_string_processor/broken_code.rs rename to 06-intermediate-rust/supplementary/exercises/exercise_1_string_processor/broken_code.rs diff --git a/06-advanced-functions/exercises/exercise_1_string_processor/expected_output.txt b/06-intermediate-rust/supplementary/exercises/exercise_1_string_processor/expected_output.txt similarity index 100% rename from 06-advanced-functions/exercises/exercise_1_string_processor/expected_output.txt rename to 06-intermediate-rust/supplementary/exercises/exercise_1_string_processor/expected_output.txt diff --git a/06-advanced-functions/exercises/exercise_1_string_processor/hints.md b/06-intermediate-rust/supplementary/exercises/exercise_1_string_processor/hints.md similarity index 100% rename from 06-advanced-functions/exercises/exercise_1_string_processor/hints.md rename to 06-intermediate-rust/supplementary/exercises/exercise_1_string_processor/hints.md diff --git a/06-advanced-functions/exercises/exercise_1_string_processor/problem_statement.md b/06-intermediate-rust/supplementary/exercises/exercise_1_string_processor/problem_statement.md similarity index 100% rename from 06-advanced-functions/exercises/exercise_1_string_processor/problem_statement.md rename to 06-intermediate-rust/supplementary/exercises/exercise_1_string_processor/problem_statement.md diff --git a/06-advanced-functions/exercises/exercise_2_generic_container/broken_code.rs b/06-intermediate-rust/supplementary/exercises/exercise_2_generic_container/broken_code.rs similarity index 100% rename from 06-advanced-functions/exercises/exercise_2_generic_container/broken_code.rs rename to 06-intermediate-rust/supplementary/exercises/exercise_2_generic_container/broken_code.rs diff --git a/06-advanced-functions/exercises/exercise_2_generic_container/expected_output.txt b/06-intermediate-rust/supplementary/exercises/exercise_2_generic_container/expected_output.txt similarity index 100% rename from 06-advanced-functions/exercises/exercise_2_generic_container/expected_output.txt rename to 06-intermediate-rust/supplementary/exercises/exercise_2_generic_container/expected_output.txt diff --git a/06-advanced-functions/exercises/exercise_2_generic_container/hints.md b/06-intermediate-rust/supplementary/exercises/exercise_2_generic_container/hints.md similarity index 100% rename from 06-advanced-functions/exercises/exercise_2_generic_container/hints.md rename to 06-intermediate-rust/supplementary/exercises/exercise_2_generic_container/hints.md diff --git a/06-advanced-functions/exercises/exercise_2_generic_container/problem_statement.md b/06-intermediate-rust/supplementary/exercises/exercise_2_generic_container/problem_statement.md similarity index 100% rename from 06-advanced-functions/exercises/exercise_2_generic_container/problem_statement.md rename to 06-intermediate-rust/supplementary/exercises/exercise_2_generic_container/problem_statement.md diff --git a/06-advanced-functions/exercises/exercise_3_enum_result_handler/broken_code.rs b/06-intermediate-rust/supplementary/exercises/exercise_3_enum_result_handler/broken_code.rs similarity index 100% rename from 06-advanced-functions/exercises/exercise_3_enum_result_handler/broken_code.rs rename to 06-intermediate-rust/supplementary/exercises/exercise_3_enum_result_handler/broken_code.rs diff --git a/06-advanced-functions/exercises/exercise_3_enum_result_handler/expected_output.txt b/06-intermediate-rust/supplementary/exercises/exercise_3_enum_result_handler/expected_output.txt similarity index 100% rename from 06-advanced-functions/exercises/exercise_3_enum_result_handler/expected_output.txt rename to 06-intermediate-rust/supplementary/exercises/exercise_3_enum_result_handler/expected_output.txt diff --git a/06-advanced-functions/exercises/exercise_3_enum_result_handler/hints.md b/06-intermediate-rust/supplementary/exercises/exercise_3_enum_result_handler/hints.md similarity index 100% rename from 06-advanced-functions/exercises/exercise_3_enum_result_handler/hints.md rename to 06-intermediate-rust/supplementary/exercises/exercise_3_enum_result_handler/hints.md diff --git a/06-advanced-functions/exercises/exercise_3_enum_result_handler/problem_statement.md b/06-intermediate-rust/supplementary/exercises/exercise_3_enum_result_handler/problem_statement.md similarity index 100% rename from 06-advanced-functions/exercises/exercise_3_enum_result_handler/problem_statement.md rename to 06-intermediate-rust/supplementary/exercises/exercise_3_enum_result_handler/problem_statement.md diff --git a/06-advanced-functions/exercises/exercise_4_ownership_transfer/broken_code.rs b/06-intermediate-rust/supplementary/exercises/exercise_4_ownership_transfer/broken_code.rs similarity index 100% rename from 06-advanced-functions/exercises/exercise_4_ownership_transfer/broken_code.rs rename to 06-intermediate-rust/supplementary/exercises/exercise_4_ownership_transfer/broken_code.rs diff --git a/06-advanced-functions/exercises/exercise_4_ownership_transfer/expected_output.txt b/06-intermediate-rust/supplementary/exercises/exercise_4_ownership_transfer/expected_output.txt similarity index 100% rename from 06-advanced-functions/exercises/exercise_4_ownership_transfer/expected_output.txt rename to 06-intermediate-rust/supplementary/exercises/exercise_4_ownership_transfer/expected_output.txt diff --git a/06-advanced-functions/exercises/exercise_4_ownership_transfer/hints.md b/06-intermediate-rust/supplementary/exercises/exercise_4_ownership_transfer/hints.md similarity index 100% rename from 06-advanced-functions/exercises/exercise_4_ownership_transfer/hints.md rename to 06-intermediate-rust/supplementary/exercises/exercise_4_ownership_transfer/hints.md diff --git a/06-advanced-functions/exercises/exercise_4_ownership_transfer/problem_statement.md b/06-intermediate-rust/supplementary/exercises/exercise_4_ownership_transfer/problem_statement.md similarity index 100% rename from 06-advanced-functions/exercises/exercise_4_ownership_transfer/problem_statement.md rename to 06-intermediate-rust/supplementary/exercises/exercise_4_ownership_transfer/problem_statement.md diff --git a/06-advanced-functions/generics/README.md b/06-intermediate-rust/supplementary/generics/README.md similarity index 100% rename from 06-advanced-functions/generics/README.md rename to 06-intermediate-rust/supplementary/generics/README.md diff --git a/06-advanced-functions/generics/examples/container_operations.rs b/06-intermediate-rust/supplementary/generics/examples/container_operations.rs similarity index 100% rename from 06-advanced-functions/generics/examples/container_operations.rs rename to 06-intermediate-rust/supplementary/generics/examples/container_operations.rs diff --git a/06-advanced-functions/generics/key_takeaways.md b/06-intermediate-rust/supplementary/generics/key_takeaways.md similarity index 100% rename from 06-advanced-functions/generics/key_takeaways.md rename to 06-intermediate-rust/supplementary/generics/key_takeaways.md diff --git a/06-advanced-functions/ownership_and_borrowing/README.md b/06-intermediate-rust/supplementary/ownership_and_borrowing/README.md similarity index 100% rename from 06-advanced-functions/ownership_and_borrowing/README.md rename to 06-intermediate-rust/supplementary/ownership_and_borrowing/README.md diff --git a/06-advanced-functions/ownership_and_borrowing/examples/string_manipulation.rs b/06-intermediate-rust/supplementary/ownership_and_borrowing/examples/string_manipulation.rs similarity index 100% rename from 06-advanced-functions/ownership_and_borrowing/examples/string_manipulation.rs rename to 06-intermediate-rust/supplementary/ownership_and_borrowing/examples/string_manipulation.rs diff --git a/06-advanced-functions/ownership_and_borrowing/key_takeaways.md b/06-intermediate-rust/supplementary/ownership_and_borrowing/key_takeaways.md similarity index 100% rename from 06-advanced-functions/ownership_and_borrowing/key_takeaways.md rename to 06-intermediate-rust/supplementary/ownership_and_borrowing/key_takeaways.md diff --git a/06-advanced-functions/traits_and_polymorphism/README.md b/06-intermediate-rust/supplementary/traits_and_polymorphism/README.md similarity index 100% rename from 06-advanced-functions/traits_and_polymorphism/README.md rename to 06-intermediate-rust/supplementary/traits_and_polymorphism/README.md diff --git a/06-advanced-functions/traits_and_polymorphism/examples/logger_system.rs b/06-intermediate-rust/supplementary/traits_and_polymorphism/examples/logger_system.rs similarity index 100% rename from 06-advanced-functions/traits_and_polymorphism/examples/logger_system.rs rename to 06-intermediate-rust/supplementary/traits_and_polymorphism/examples/logger_system.rs diff --git a/06-advanced-functions/traits_and_polymorphism/key_takeaways.md b/06-intermediate-rust/supplementary/traits_and_polymorphism/key_takeaways.md similarity index 100% rename from 06-advanced-functions/traits_and_polymorphism/key_takeaways.md rename to 06-intermediate-rust/supplementary/traits_and_polymorphism/key_takeaways.md diff --git a/06-intermediate-rust/traits_and_polymorphism/metadata.json b/06-intermediate-rust/traits_and_polymorphism/metadata.json new file mode 100644 index 0000000..6679855 --- /dev/null +++ b/06-intermediate-rust/traits_and_polymorphism/metadata.json @@ -0,0 +1,27 @@ +{ + "$schema": "../../schemas/topic-metadata-v1.schema.json", + "schema_version": 1, + "id": "06-traits", + "title": "Traits and Polymorphism", + "status": "review", + "level": "intermediate", + "estimated_minutes": 90, + "prerequisites": ["01-ownership", "06-generics"], + "concepts": ["traits", "trait-bounds", "static-dispatch", "dynamic-dispatch", "trait-objects"], + "tracks": ["core", "java", "python", "cpp", "go"], + "learning_objectives": [ + "Define shared behavior with a trait and implement it for local types.", + "Use impl Trait and generic trait bounds for static dispatch.", + "Use trait objects when runtime polymorphism is appropriate.", + "Explain the tradeoff between static and dynamic dispatch." + ], + "website": { + "published": false, + "order": null + }, + "validation": { + "content_rubric": "pending", + "examples": "passed", + "exercises": "pending" + } +} diff --git a/07-advanced-concepts/README.md b/07-advanced-concepts/README.md index 30ad648..4a76d9a 100644 --- a/07-advanced-concepts/README.md +++ b/07-advanced-concepts/README.md @@ -52,6 +52,8 @@ This section contains expert-level Rust topics that go beyond traditional applic **Key Topics**: REST patterns, middleware, production web stack +See [Project Architecture and Observability](../docs/production/project-architecture-and-observability.md) for a production-oriented way to extend the Axum example without overstating what it already provides. + --- ### advanced_async/ diff --git a/07-advanced-concepts/database_integration/01-sqlx-basics/README.md b/07-advanced-concepts/database_integration/01-sqlx-basics/README.md index f202e88..505d76f 100644 --- a/07-advanced-concepts/database_integration/01-sqlx-basics/README.md +++ b/07-advanced-concepts/database_integration/01-sqlx-basics/README.md @@ -1,87 +1,37 @@ -# SQLx Basics - Compile-Time Verified Queries +# SQLx basics -Demonstrates SQLx's compile-time query verification, ensuring SQL correctness before runtime. +This example uses PostgreSQL, SQLx connection pooling, typed row mapping, and parameter binding. It deliberately uses `query` and `query_as` rather than SQLx's compile-time query macros, so formatting, linting, tests, and compilation do not require a running database. -## Features +## Build checks -- Compile-time SQL verification -- Type-safe query results -- Async/await support -- Connection pooling -- Migrations - -## Setup +The default checks need Rust and the downloaded Cargo dependencies, but no database service: ```bash -# Start PostgreSQL -docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=password postgres:15 - -# Create .env file -echo "DATABASE_URL=postgres://postgres:password@localhost/testdb" > .env - -# Create database -sqlx database create - -# Run migrations -sqlx migrate run +cargo fmt --all -- --check +cargo clippy --all-targets --all-features -- -D warnings +cargo test --all-targets ``` -## Building +## Run the example -```bash -# Requires DATABASE_URL environment variable -cargo build - -# For offline mode (no database required) -cargo sqlx prepare -cargo build --offline -``` +Start PostgreSQL and create a database before running the program: -## Key Concepts - -### Compile-Time Query Verification - -SQLx verifies queries at compile time by connecting to your database: - -```rust -// This fails to compile if: -// - Table doesn't exist -// - Column names are wrong -// - Types don't match -let user = sqlx::query_as!( - User, - "SELECT id, name, email FROM users WHERE id = $1", - user_id -) -.fetch_one(&pool) -.await?; +```bash +docker run --name rust-lab-postgres -e POSTGRES_PASSWORD=password -e POSTGRES_DB=testdb -p 5432:5432 -d postgres:15 +export DATABASE_URL=postgres://postgres:password@localhost/testdb +cargo run ``` -### Type Safety - -Rust types are automatically derived from database schema: +The program creates its `users` table on startup. Reusing the same database will preserve rows from earlier runs, so use a disposable database when you want repeatable output. -```rust -#[derive(sqlx::FromRow)] -struct User { - id: i32, // INTEGER - name: String, // VARCHAR - email: String, // VARCHAR - created_at: DateTime, // TIMESTAMP -} -``` +## Why the queries are checked at runtime -## Advantages over ORM +SQLx's `query!` and `query_as!` macros validate SQL against a live schema during compilation, or against metadata produced by `cargo sqlx prepare`. That is useful in an application with migrations and a committed offline cache. This standalone lesson has neither, so requiring those macros made an ordinary `cargo check` depend on an unconfigured PostgreSQL service. -✅ Write raw SQL (full database features) -✅ Compile-time verification -✅ No runtime query parsing -✅ Better performance -✅ Simpler debugging +The example keeps typed result mapping through `#[derive(sqlx::FromRow)]` and `query_as::<_, User>()`. SQL syntax and schema compatibility are checked when the query runs. -## Next Steps +## Exercises -- Add more complex queries -- Implement transactions -- Try different databases (MySQL, SQLite) -- Add full-text search +- Return the inserted user's creation timestamp. +- Wrap a group of updates in a transaction. +- Add a migration directory and compare runtime queries with SQLx's offline compile-time verification. diff --git a/07-advanced-concepts/database_integration/01-sqlx-basics/src/main.rs b/07-advanced-concepts/database_integration/01-sqlx-basics/src/main.rs index 7f838b2..8ec37fa 100644 --- a/07-advanced-concepts/database_integration/01-sqlx-basics/src/main.rs +++ b/07-advanced-concepts/database_integration/01-sqlx-basics/src/main.rs @@ -13,8 +13,7 @@ struct User { async fn main() -> Result<(), sqlx::Error> { dotenv::dotenv().ok(); - let database_url = env::var("DATABASE_URL") - .expect("DATABASE_URL must be set"); + let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); // Create connection pool let pool = PgPoolOptions::new() @@ -67,7 +66,7 @@ async fn create_table(pool: &PgPool) -> Result<(), sqlx::Error> { email VARCHAR(255) UNIQUE NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) - "# + "#, ) .execute(pool) .await?; @@ -77,12 +76,11 @@ async fn create_table(pool: &PgPool) -> Result<(), sqlx::Error> { } async fn insert_user(pool: &PgPool, name: &str, email: &str) -> Result { - let user = sqlx::query_as!( - User, + let user = sqlx::query_as::<_, User>( "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id, name, email", - name, - email ) + .bind(name) + .bind(email) .fetch_one(pool) .await?; @@ -91,12 +89,9 @@ async fn insert_user(pool: &PgPool, name: &str, email: &str) -> Result Result<(), sqlx::Error> { - let users = sqlx::query_as!( - User, - "SELECT id, name, email FROM users ORDER BY id" - ) - .fetch_all(pool) - .await?; + let users = sqlx::query_as::<_, User>("SELECT id, name, email FROM users ORDER BY id") + .fetch_all(pool) + .await?; for user in users { println!(" [{}] {} <{}>", user.id, user.name, user.email); @@ -106,25 +101,20 @@ async fn list_users(pool: &PgPool) -> Result<(), sqlx::Error> { } async fn find_by_email(pool: &PgPool, email: &str) -> Result, sqlx::Error> { - let user = sqlx::query_as!( - User, - "SELECT id, name, email FROM users WHERE email = $1", - email - ) - .fetch_optional(pool) - .await?; + let user = sqlx::query_as::<_, User>("SELECT id, name, email FROM users WHERE email = $1") + .bind(email) + .fetch_optional(pool) + .await?; Ok(user) } async fn update_user_name(pool: &PgPool, id: i32, new_name: &str) -> Result<(), sqlx::Error> { - sqlx::query!( - "UPDATE users SET name = $1 WHERE id = $2", - new_name, - id - ) - .execute(pool) - .await?; + sqlx::query("UPDATE users SET name = $1 WHERE id = $2") + .bind(new_name) + .bind(id) + .execute(pool) + .await?; println!("✅ Updated user {}", id); Ok(()) @@ -140,7 +130,8 @@ async fn count_users(pool: &PgPool) -> Result { } async fn delete_user(pool: &PgPool, id: i32) -> Result<(), sqlx::Error> { - sqlx::query!("DELETE FROM users WHERE id = $1", id) + sqlx::query("DELETE FROM users WHERE id = $1") + .bind(id) .execute(pool) .await?; diff --git a/07-advanced-concepts/embedded_rust/02-blinky/.cargo/config.toml b/07-advanced-concepts/embedded_rust/02-blinky/.cargo/config.toml new file mode 100644 index 0000000..ff32d13 --- /dev/null +++ b/07-advanced-concepts/embedded_rust/02-blinky/.cargo/config.toml @@ -0,0 +1,5 @@ +[build] +target = "thumbv7em-none-eabihf" + +[target.thumbv7em-none-eabihf] +rustflags = ["-C", "link-arg=-Tlink.x"] diff --git a/07-advanced-concepts/embedded_rust/02-blinky/README.md b/07-advanced-concepts/embedded_rust/02-blinky/README.md index c58f079..cd4e6bf 100644 --- a/07-advanced-concepts/embedded_rust/02-blinky/README.md +++ b/07-advanced-concepts/embedded_rust/02-blinky/README.md @@ -1,58 +1,40 @@ -# Blinky - LED Blinking Example +# Blinky on an STM32F401 -The "Hello World" of embedded systems. Blink an LED on a microcontroller. +This `no_std` example blinks the PA5 LED on an STM32F401-based Nucleo board. Its dependencies and target configuration are board-specific; it is not a portable example for RP2040, AVR, or ESP32 boards. -## Supported Boards +## Requirements -- **STM32 Nucleo-64** (F401RE, F411RE, etc.) -- **Raspberry Pi Pico** (RP2040) -- **Arduino Uno** (AVR - experimental) -- **ESP32-C3** (RISC-V) +- The `thumbv7em-none-eabihf` Rust target +- An STM32F401-based board when flashing the program +- A compatible flashing tool such as `cargo-flash` or `probe-rs` -## What This Does +Install the compilation target once: -Toggles an on-board LED every 1 second, demonstrating: -- no_std environment -- GPIO output control -- Delay timers -- Infinite loop patterns - -## Building & Flashing - -### For STM32: ```bash -cargo build --release -cargo flash --chip STM32F401RETx +rustup target add thumbv7em-none-eabihf ``` -### For RP2040 (Pico): +The local `.cargo/config.toml` selects that target and passes the Cortex-M linker script automatically. + +## Check and build + ```bash +cargo check cargo build --release -elf2uf2-rs target/thumbv6m-none-eabi/release/blinky -# Copy UF2 file to Pico ``` -### For ESP32-C3: +To flash a connected Nucleo-F401RE with `cargo-flash`: + ```bash -cargo espflash flash --release --monitor +cargo flash --release --chip STM32F401RETx ``` -## Key Concepts - -- **#![no_std]** - No standard library -- **#![no_main]** - Custom entry point -- **Panic handler** - What happens on panic -- **GPIO abstraction** - Portable LED control -- **Delay** - Blocking delays without OS - -## Memory Usage - -- Flash: ~4-8 KB -- RAM: <1 KB +## What the example demonstrates -## Next Steps +- A `#![no_std]` and `#![no_main]` binary +- A Cortex-M runtime entry point +- Peripheral ownership through the STM32 peripheral access crate +- GPIO output configuration +- A hardware-timer delay in a non-terminating loop -- Change blink frequency -- Add multiple LEDs -- Use PWM for breathing effect -- Respond to button presses +The target configuration is part of the example. Running `cargo check` for the host target is not a meaningful validation of this binary because the host supplies `std`, an operating-system entry point, and a different instruction set. diff --git a/07-advanced-concepts/embedded_rust/02-blinky/src/main.rs b/07-advanced-concepts/embedded_rust/02-blinky/src/main.rs index e1f4d6c..7149f55 100644 --- a/07-advanced-concepts/embedded_rust/02-blinky/src/main.rs +++ b/07-advanced-concepts/embedded_rust/02-blinky/src/main.rs @@ -1,8 +1,8 @@ #![no_std] #![no_main] -use panic_halt as _; use cortex_m_rt::entry; +use panic_halt as _; use stm32f4xx_hal::{pac, prelude::*}; #[entry] diff --git a/07-advanced-concepts/modern_web_apis/02-axum-api/README.md b/07-advanced-concepts/modern_web_apis/02-axum-api/README.md index 437ca92..f862e63 100644 --- a/07-advanced-concepts/modern_web_apis/02-axum-api/README.md +++ b/07-advanced-concepts/modern_web_apis/02-axum-api/README.md @@ -24,6 +24,14 @@ DELETE /api/users/:id # Delete user ## Running +An ordinary build check does not require PostgreSQL because the handlers use typed runtime SQLx queries: + +```bash +cargo check +``` + +Running the server does require PostgreSQL: + ```bash # Start PostgreSQL docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=password postgres:15 @@ -70,6 +78,8 @@ curl -X DELETE http://localhost:3000/api/users/1 - **Errors** - Custom error types - **Middleware** - Cross-cutting concerns +For a production-oriented extension of these boundaries, including the limits of the current tracing and health-check examples, read [Project Architecture and Observability](../../../docs/production/project-architecture-and-observability.md). + ## Key Learnings - Axum's type-safe extractors diff --git a/07-advanced-concepts/modern_web_apis/02-axum-api/src/main.rs b/07-advanced-concepts/modern_web_apis/02-axum-api/src/main.rs index 833255d..db1b7ad 100644 --- a/07-advanced-concepts/modern_web_apis/02-axum-api/src/main.rs +++ b/07-advanced-concepts/modern_web_apis/02-axum-api/src/main.rs @@ -1,13 +1,14 @@ use axum::{ extract::{Path, State}, http::StatusCode, - routing::{get, post}, + routing::get, Json, Router, }; use serde::{Deserialize, Serialize}; use sqlx::postgres::PgPoolOptions; use sqlx::PgPool; use std::net::SocketAddr; +use tokio::net::TcpListener; use tower_http::cors::{Any, CorsLayer}; use tower_http::trace::TraceLayer; @@ -72,10 +73,10 @@ async fn main() { let addr = SocketAddr::from(([0, 0, 0, 0], 3000)); println!("🚀 Server running on http://{}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = TcpListener::bind(addr) .await - .unwrap(); + .expect("Failed to bind address"); + axum::serve(listener, app).await.expect("Server failed"); } async fn health_check() -> Json { @@ -86,7 +87,7 @@ async fn health_check() -> Json { } async fn list_users(State(state): State) -> Result>, StatusCode> { - let users = sqlx::query_as!(User, "SELECT id, name, email FROM users ORDER BY id") + let users = sqlx::query_as::<_, User>("SELECT id, name, email FROM users ORDER BY id") .fetch_all(&state.db) .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; @@ -98,7 +99,8 @@ async fn get_user( State(state): State, Path(id): Path, ) -> Result, StatusCode> { - let user = sqlx::query_as!(User, "SELECT id, name, email FROM users WHERE id = $1", id) + let user = sqlx::query_as::<_, User>("SELECT id, name, email FROM users WHERE id = $1") + .bind(id) .fetch_one(&state.db) .await .map_err(|_| StatusCode::NOT_FOUND)?; @@ -110,12 +112,11 @@ async fn create_user( State(state): State, Json(payload): Json, ) -> Result<(StatusCode, Json), StatusCode> { - let user = sqlx::query_as!( - User, + let user = sqlx::query_as::<_, User>( "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id, name, email", - payload.name, - payload.email ) + .bind(payload.name) + .bind(payload.email) .fetch_one(&state.db) .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; @@ -128,13 +129,12 @@ async fn update_user( Path(id): Path, Json(payload): Json, ) -> Result, StatusCode> { - let user = sqlx::query_as!( - User, + let user = sqlx::query_as::<_, User>( "UPDATE users SET name = $1, email = $2 WHERE id = $3 RETURNING id, name, email", - payload.name, - payload.email, - id ) + .bind(payload.name) + .bind(payload.email) + .bind(id) .fetch_one(&state.db) .await .map_err(|_| StatusCode::NOT_FOUND)?; @@ -146,7 +146,8 @@ async fn delete_user( State(state): State, Path(id): Path, ) -> Result { - let result = sqlx::query!("DELETE FROM users WHERE id = $1", id) + let result = sqlx::query("DELETE FROM users WHERE id = $1") + .bind(id) .execute(&state.db) .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; diff --git a/07-advanced-concepts/performance_optimization/01-benchmarking/BENCHMARKING_PROTOCOL.md b/07-advanced-concepts/performance_optimization/01-benchmarking/BENCHMARKING_PROTOCOL.md new file mode 100644 index 0000000..58d3b1a --- /dev/null +++ b/07-advanced-concepts/performance_optimization/01-benchmarking/BENCHMARKING_PROTOCOL.md @@ -0,0 +1,35 @@ +# Reproducible Benchmarking Protocol + +The benchmarks in this directory compare alternative implementations; they do not establish a universal ranking. Treat every result as a measurement of this machine, compiler, dependency set, and input distribution. + +## Run a baseline + +Run from this directory with a release toolchain. Close unnecessary workloads where practical, record the command and machine details, and use the same command for the comparison. + +```bash +cargo bench --bench algorithms -- --save-baseline before-change +cargo bench --bench data_structures -- --save-baseline before-change +``` + +After a focused implementation change, compare it to that baseline. + +```bash +cargo bench --bench algorithms -- --baseline before-change +cargo bench --bench data_structures -- --baseline before-change +``` + +Criterion writes the HTML report below `target/criterion/`. Its estimates and change reports are the evidence to inspect; do not copy a single timing into documentation as a general performance claim. + +## Make a useful comparison + +Keep the operation and input data identical between candidates. Include allocation and setup only when they are part of the operation a caller pays for. The existing sorting benchmarks intentionally clone their input inside each iteration because producing a mutable unsorted input is part of sorting work; map lookup benchmarks build their maps outside the timed loop because they isolate lookup work. + +Use `black_box` around inputs and outputs when a benchmark could otherwise be optimized away. Check that each candidate produces the same result before trusting a timing. Benchmark enough input sizes to expose changes in algorithmic behavior, then profile the real application before choosing an optimization. + +## Record a result + +For a change worth keeping, capture the Rust version, target triple, CPU/operating-system context, command, benchmark group, input sizes, and Criterion change report. State the decision the measurement supports and the trade-off it does not answer, such as memory use, ordering guarantees, or readability. + +## Boundaries + +These examples are microbenchmarks. They are not a substitute for load testing an API, measuring tail latency, or collecting production telemetry. Re-run them after toolchain upgrades or a meaningful hardware change. diff --git a/07-advanced-concepts/performance_optimization/01-benchmarking/README.md b/07-advanced-concepts/performance_optimization/01-benchmarking/README.md index 6f612d3..3344838 100644 --- a/07-advanced-concepts/performance_optimization/01-benchmarking/README.md +++ b/07-advanced-concepts/performance_optimization/01-benchmarking/README.md @@ -2,6 +2,8 @@ Comprehensive benchmarking examples using criterion for statistical analysis. +Read the [reproducible benchmarking protocol](BENCHMARKING_PROTOCOL.md) before interpreting a result. It explains the commands, fairness rules, and limits of these microbenchmarks. + ## Running Benchmarks ```bash diff --git a/07-advanced-concepts/performance_optimization/01-benchmarking/benches/algorithms.rs b/07-advanced-concepts/performance_optimization/01-benchmarking/benches/algorithms.rs index ef733bc..9452c70 100644 --- a/07-advanced-concepts/performance_optimization/01-benchmarking/benches/algorithms.rs +++ b/07-advanced-concepts/performance_optimization/01-benchmarking/benches/algorithms.rs @@ -1,4 +1,4 @@ -use criterion::{black_box, criterion_group, criterion_main, Criterion, BenchmarkId}; +use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; // Fibonacci implementations fn fibonacci_recursive(n: u64) -> u64 { @@ -13,9 +13,9 @@ fn fibonacci_iterative(n: u64) -> u64 { let mut a = 0; let mut b = 1; for _ in 0..n { - let temp = a; + let next = a + b; a = b; - b = temp + b; + b = next; } a } @@ -28,7 +28,8 @@ fn fibonacci_bench(c: &mut Criterion) { b.iter(|| fibonacci_iterative(black_box(n))) }); - if *n <= 20 { // Recursive is too slow for larger n + if *n <= 20 { + // Recursive is too slow for larger n group.bench_with_input(BenchmarkId::new("recursive", n), n, |b, &n| { b.iter(|| fibonacci_recursive(black_box(n))) }); @@ -72,13 +73,17 @@ fn sorting_bench(c: &mut Criterion) { }) }); - group.bench_with_input(BenchmarkId::new("std_sort_unstable", size), &data, |b, data| { - b.iter(|| { - let mut arr = data.clone(); - arr.sort_unstable(); - arr - }) - }); + group.bench_with_input( + BenchmarkId::new("std_sort_unstable", size), + &data, + |b, data| { + b.iter(|| { + let mut arr = data.clone(); + arr.sort_unstable(); + arr + }) + }, + ); } group.finish(); @@ -118,9 +123,7 @@ fn string_concat_bench(c: &mut Criterion) { b.iter(|| concat_with_capacity(black_box(&strings))) }); - group.bench_function("join", |b| { - b.iter(|| concat_with_join(black_box(&strings))) - }); + group.bench_function("join", |b| b.iter(|| concat_with_join(black_box(&strings)))); group.finish(); } @@ -138,6 +141,7 @@ fn sum_iterator(data: &[i32]) -> i32 { data.iter().sum() } +#[allow(clippy::unnecessary_fold)] // This benchmark intentionally compares fold with Iterator::sum. fn sum_fold(data: &[i32]) -> i32 { data.iter().fold(0, |acc, &x| acc + x) } @@ -146,17 +150,11 @@ fn sum_bench(c: &mut Criterion) { let mut group = c.benchmark_group("sum"); let data: Vec = (0..10000).collect(); - group.bench_function("loop", |b| { - b.iter(|| sum_loop(black_box(&data))) - }); + group.bench_function("loop", |b| b.iter(|| sum_loop(black_box(&data)))); - group.bench_function("iterator", |b| { - b.iter(|| sum_iterator(black_box(&data))) - }); + group.bench_function("iterator", |b| b.iter(|| sum_iterator(black_box(&data)))); - group.bench_function("fold", |b| { - b.iter(|| sum_fold(black_box(&data))) - }); + group.bench_function("fold", |b| b.iter(|| sum_fold(black_box(&data)))); group.finish(); } diff --git a/07-advanced-concepts/performance_optimization/01-benchmarking/benches/data_structures.rs b/07-advanced-concepts/performance_optimization/01-benchmarking/benches/data_structures.rs index 31781ed..6e41f44 100644 --- a/07-advanced-concepts/performance_optimization/01-benchmarking/benches/data_structures.rs +++ b/07-advanced-concepts/performance_optimization/01-benchmarking/benches/data_structures.rs @@ -1,5 +1,5 @@ -use criterion::{black_box, criterion_group, criterion_main, Criterion, BenchmarkId}; -use std::collections::{HashMap, BTreeMap, HashSet, BTreeSet}; +use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; // HashMap vs BTreeMap fn map_bench(c: &mut Criterion) { @@ -7,25 +7,33 @@ fn map_bench(c: &mut Criterion) { for size in [100, 1000, 10000].iter() { // Insert - group.bench_with_input(BenchmarkId::new("hashmap_insert", size), size, |b, &size| { - b.iter(|| { - let mut map = HashMap::new(); - for i in 0..size { - map.insert(black_box(i), black_box(i * 2)); - } - map - }) - }); - - group.bench_with_input(BenchmarkId::new("btreemap_insert", size), size, |b, &size| { - b.iter(|| { - let mut map = BTreeMap::new(); - for i in 0..size { - map.insert(black_box(i), black_box(i * 2)); - } - map - }) - }); + group.bench_with_input( + BenchmarkId::new("hashmap_insert", size), + size, + |b, &size| { + b.iter(|| { + let mut map = HashMap::new(); + for i in 0..size { + map.insert(black_box(i), black_box(i * 2)); + } + map + }) + }, + ); + + group.bench_with_input( + BenchmarkId::new("btreemap_insert", size), + size, + |b, &size| { + b.iter(|| { + let mut map = BTreeMap::new(); + for i in 0..size { + map.insert(black_box(i), black_box(i * 2)); + } + map + }) + }, + ); // Lookup let hashmap: HashMap = (0..*size).map(|i| (i, i * 2)).collect(); @@ -39,13 +47,17 @@ fn map_bench(c: &mut Criterion) { }) }); - group.bench_with_input(BenchmarkId::new("btreemap_get", size), &btreemap, |b, map| { - b.iter(|| { - for i in 0..*size { - black_box(map.get(&i)); - } - }) - }); + group.bench_with_input( + BenchmarkId::new("btreemap_get", size), + &btreemap, + |b, map| { + b.iter(|| { + for i in 0..*size { + black_box(map.get(&i)); + } + }) + }, + ); } group.finish(); @@ -56,44 +68,60 @@ fn set_bench(c: &mut Criterion) { let mut group = c.benchmark_group("sets"); for size in [100, 1000, 10000].iter() { - group.bench_with_input(BenchmarkId::new("hashset_insert", size), size, |b, &size| { - b.iter(|| { - let mut set = HashSet::new(); - for i in 0..size { - set.insert(black_box(i)); - } - set - }) - }); - - group.bench_with_input(BenchmarkId::new("btreeset_insert", size), size, |b, &size| { - b.iter(|| { - let mut set = BTreeSet::new(); - for i in 0..size { - set.insert(black_box(i)); - } - set - }) - }); + group.bench_with_input( + BenchmarkId::new("hashset_insert", size), + size, + |b, &size| { + b.iter(|| { + let mut set = HashSet::new(); + for i in 0..size { + set.insert(black_box(i)); + } + set + }) + }, + ); + + group.bench_with_input( + BenchmarkId::new("btreeset_insert", size), + size, + |b, &size| { + b.iter(|| { + let mut set = BTreeSet::new(); + for i in 0..size { + set.insert(black_box(i)); + } + set + }) + }, + ); let hashset: HashSet = (0..*size).collect(); let btreeset: BTreeSet = (0..*size).collect(); - group.bench_with_input(BenchmarkId::new("hashset_contains", size), &hashset, |b, set| { - b.iter(|| { - for i in 0..*size { - black_box(set.contains(&i)); - } - }) - }); - - group.bench_with_input(BenchmarkId::new("btreeset_contains", size), &btreeset, |b, set| { - b.iter(|| { - for i in 0..*size { - black_box(set.contains(&i)); - } - }) - }); + group.bench_with_input( + BenchmarkId::new("hashset_contains", size), + &hashset, + |b, set| { + b.iter(|| { + for i in 0..*size { + black_box(set.contains(&i)); + } + }) + }, + ); + + group.bench_with_input( + BenchmarkId::new("btreeset_contains", size), + &btreeset, + |b, set| { + b.iter(|| { + for i in 0..*size { + black_box(set.contains(&i)); + } + }) + }, + ); } group.finish(); @@ -104,29 +132,37 @@ fn vec_bench(c: &mut Criterion) { let mut group = c.benchmark_group("vec"); for size in [100, 1000, 10000].iter() { - group.bench_with_input(BenchmarkId::new("push_no_capacity", size), size, |b, &size| { - b.iter(|| { - let mut v = Vec::new(); - for i in 0..size { - v.push(black_box(i)); - } - v - }) - }); - - group.bench_with_input(BenchmarkId::new("push_with_capacity", size), size, |b, &size| { - b.iter(|| { - let mut v = Vec::with_capacity(size); - for i in 0..size { - v.push(black_box(i)); - } - v - }) - }); + group.bench_with_input( + BenchmarkId::new("push_no_capacity", size), + size, + |b, &size| { + b.iter(|| { + let mut v = Vec::new(); + for i in 0..size { + v.push(black_box(i)); + } + v + }) + }, + ); + + group.bench_with_input( + BenchmarkId::new("push_with_capacity", size), + size, + |b, &size| { + b.iter(|| { + let mut v = Vec::with_capacity(size); + for i in 0..size { + v.push(black_box(i)); + } + v + }) + }, + ); group.bench_with_input(BenchmarkId::new("from_iter", size), size, |b, &size| { b.iter(|| { - let v: Vec = (0..size).collect(); + let v: Vec = (0..size).map(|value| value as i32).collect(); v }) }); diff --git a/07-advanced-concepts/performance_optimization/03-simd-optimization/benches/simd_bench.rs b/07-advanced-concepts/performance_optimization/03-simd-optimization/benches/simd_bench.rs index 71924d1..ab6cc03 100644 --- a/07-advanced-concepts/performance_optimization/03-simd-optimization/benches/simd_bench.rs +++ b/07-advanced-concepts/performance_optimization/03-simd-optimization/benches/simd_bench.rs @@ -1,4 +1,4 @@ -use criterion::{black_box, criterion_group, criterion_main, Criterion, BenchmarkId}; +use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; use simd_optimization::*; fn dot_product_bench(c: &mut Criterion) { @@ -8,17 +8,23 @@ fn dot_product_bench(c: &mut Criterion) { let a: Vec = (0..*size).map(|x| x as f32).collect(); let b: Vec = (0..*size).map(|x| (x * 2) as f32).collect(); - group.bench_with_input(BenchmarkId::new("scalar", size), &(&a, &b), |bench, (a, b)| { - bench.iter(|| dot_product_scalar(black_box(a), black_box(b))) - }); - - group.bench_with_input(BenchmarkId::new("simd4", size), &(&a, &b), |bench, (a, b)| { - bench.iter(|| dot_product_simd4(black_box(a), black_box(b))) - }); - - group.bench_with_input(BenchmarkId::new("simd8", size), &(&a, &b), |bench, (a, b)| { - bench.iter(|| dot_product_simd8(black_box(a), black_box(b))) - }); + group.bench_with_input( + BenchmarkId::new("scalar", size), + &(&a, &b), + |bench, (a, b)| bench.iter(|| dot_product_scalar(black_box(a), black_box(b))), + ); + + group.bench_with_input( + BenchmarkId::new("simd4", size), + &(&a, &b), + |bench, (a, b)| bench.iter(|| dot_product_simd4(black_box(a), black_box(b))), + ); + + group.bench_with_input( + BenchmarkId::new("simd8", size), + &(&a, &b), + |bench, (a, b)| bench.iter(|| dot_product_simd8(black_box(a), black_box(b))), + ); } group.finish(); @@ -31,13 +37,17 @@ fn vec_add_bench(c: &mut Criterion) { let a: Vec = (0..*size).map(|x| x as f32).collect(); let b: Vec = (0..*size).map(|x| (x * 2) as f32).collect(); - group.bench_with_input(BenchmarkId::new("scalar", size), &(&a, &b), |bench, (a, b)| { - bench.iter(|| vec_add_scalar(black_box(a), black_box(b))) - }); - - group.bench_with_input(BenchmarkId::new("simd", size), &(&a, &b), |bench, (a, b)| { - bench.iter(|| vec_add_simd(black_box(a), black_box(b))) - }); + group.bench_with_input( + BenchmarkId::new("scalar", size), + &(&a, &b), + |bench, (a, b)| bench.iter(|| vec_add_scalar(black_box(a), black_box(b))), + ); + + group.bench_with_input( + BenchmarkId::new("simd", size), + &(&a, &b), + |bench, (a, b)| bench.iter(|| vec_add_simd(black_box(a), black_box(b))), + ); } group.finish(); @@ -61,5 +71,10 @@ fn sum_of_squares_bench(c: &mut Criterion) { group.finish(); } -criterion_group!(benches, dot_product_bench, vec_add_bench, sum_of_squares_bench); +criterion_group!( + benches, + dot_product_bench, + vec_add_bench, + sum_of_squares_bench +); criterion_main!(benches); diff --git a/07-advanced-concepts/performance_optimization/03-simd-optimization/src/lib.rs b/07-advanced-concepts/performance_optimization/03-simd-optimization/src/lib.rs index fd51a61..b160a01 100644 --- a/07-advanced-concepts/performance_optimization/03-simd-optimization/src/lib.rs +++ b/07-advanced-concepts/performance_optimization/03-simd-optimization/src/lib.rs @@ -5,10 +5,7 @@ // Scalar dot product pub fn dot_product_scalar(a: &[f32], b: &[f32]) -> f32 { assert_eq!(a.len(), b.len()); - a.iter() - .zip(b.iter()) - .map(|(x, y)| x * y) - .sum() + a.iter().zip(b.iter()).map(|(x, y)| x * y).sum() } // Optimized dot product with manual loop unrolling @@ -29,7 +26,7 @@ pub fn dot_product_simd4(a: &[f32], b: &[f32]) -> f32 { sum3 += a[idx + 3] * b[idx + 3]; } - let mut result = sum0 + sum1 + sum2 + sum3; + let result = sum0 + sum1 + sum2 + sum3; let remainder: f32 = a[chunks * 4..] .iter() @@ -66,7 +63,7 @@ pub fn dot_product_simd8(a: &[f32], b: &[f32]) -> f32 { sum7 += a[idx + 7] * b[idx + 7]; } - let mut result = sum0 + sum1 + sum2 + sum3 + sum4 + sum5 + sum6 + sum7; + let result = sum0 + sum1 + sum2 + sum3 + sum4 + sum5 + sum6 + sum7; let remainder: f32 = a[chunks * 8..] .iter() @@ -80,10 +77,7 @@ pub fn dot_product_simd8(a: &[f32], b: &[f32]) -> f32 { // Vector addition - scalar pub fn vec_add_scalar(a: &[f32], b: &[f32]) -> Vec { assert_eq!(a.len(), b.len()); - a.iter() - .zip(b.iter()) - .map(|(x, y)| x + y) - .collect() + a.iter().zip(b.iter()).map(|(x, y)| x + y).collect() } // Vector addition - optimized with loop unrolling @@ -143,8 +137,8 @@ pub fn sum_of_squares_simd(data: &[f32]) -> f32 { let mut result = sum0 + sum1 + sum2 + sum3 + sum4 + sum5 + sum6 + sum7; - for i in chunks * 8..data.len() { - result += data[i] * data[i]; + for &value in data.iter().skip(chunks * 8) { + result += value * value; } result diff --git a/07-advanced-concepts/performance_optimization/03-simd-optimization/src/main.rs b/07-advanced-concepts/performance_optimization/03-simd-optimization/src/main.rs index 8fc8a1b..cf8e7a5 100644 --- a/07-advanced-concepts/performance_optimization/03-simd-optimization/src/main.rs +++ b/07-advanced-concepts/performance_optimization/03-simd-optimization/src/main.rs @@ -29,8 +29,14 @@ fn main() { let result_scalar_add = simd_lib::vec_add_scalar(&a, &b); let result_simd_add = simd_lib::vec_add_simd(&a, &b); - println!("Scalar addition: first 5 elements = {:?}", &result_scalar_add[0..5]); - println!("Optimized addition: first 5 elements = {:?}", &result_simd_add[0..5]); + println!( + "Scalar addition: first 5 elements = {:?}", + &result_scalar_add[0..5] + ); + println!( + "Optimized addition: first 5 elements = {:?}", + &result_simd_add[0..5] + ); assert_eq!(result_scalar_add, result_simd_add); // Example 3: Sum of Squares diff --git a/07-advanced-concepts/performance_optimization/README.md b/07-advanced-concepts/performance_optimization/README.md index b6313df..470efda 100644 --- a/07-advanced-concepts/performance_optimization/README.md +++ b/07-advanced-concepts/performance_optimization/README.md @@ -618,6 +618,8 @@ unsafe fn sum_avx2(data: &[f32]) -> f32 { } ``` +Safety contract: a caller may invoke an AVX2 implementation only after runtime feature detection confirms AVX2 on the executing CPU. The function may read only within `data` and must preserve the scalar implementation's result semantics, including its floating-point trade-offs. Keep a portable fallback and expose a safe dispatch function rather than making ordinary callers uphold this contract. + ### ARM NEON ```rust @@ -631,6 +633,10 @@ unsafe fn sum_neon(data: &[f32]) -> f32 { } ``` +Safety contract: a caller may invoke a NEON implementation only on an AArch64 target where the required feature is available. The implementation must not form invalid vector loads from `data`, and it must retain a portable fallback for other targets. These are sketches; they are not complete runnable SIMD implementations. + +See [Unsafe Safety Contracts](../../docs/production/unsafe-safety-contracts.md) for the review standard used by this repository. + ## Tools and Crates ### Profiling diff --git a/07-advanced-concepts/procedural_macros/01-derive-macro/example/src/main.rs b/07-advanced-concepts/procedural_macros/01-derive-macro/example/src/main.rs index 62da9ea..5768ab0 100644 --- a/07-advanced-concepts/procedural_macros/01-derive-macro/example/src/main.rs +++ b/07-advanced-concepts/procedural_macros/01-derive-macro/example/src/main.rs @@ -1,4 +1,4 @@ -use my_derive::{HelloWorld, FieldNames, EnumIter, CustomDefault}; +use my_derive::{CustomDefault, EnumIter, FieldNames, HelloWorld}; // Define the trait that our derive macro will implement trait HelloWorld { @@ -67,6 +67,7 @@ fn main() { age: 30, }; person.hello_world(); + println!("Person data: {} ({})", person.name, person.age); let robot = Robot; robot.hello_world(); @@ -77,7 +78,17 @@ fn main() { println!("=== 2. FieldNames Derive ==="); let field_names = User::field_names(); println!("User fields: {:?}", field_names); - println!("Field count: {}", field_names.len()); + println!("Field count: {}", User::field_count()); + let sample_user = User { + id: 1, + username: "alice".to_string(), + email: "alice@example.com".to_string(), + is_active: true, + }; + println!( + "Sample user: {} {} {} {}", + sample_user.id, sample_user.username, sample_user.email, sample_user.is_active + ); println!(); diff --git a/07-advanced-concepts/procedural_macros/01-derive-macro/my-derive/src/lib.rs b/07-advanced-concepts/procedural_macros/01-derive-macro/my-derive/src/lib.rs index cdd0117..7f5f523 100644 --- a/07-advanced-concepts/procedural_macros/01-derive-macro/my-derive/src/lib.rs +++ b/07-advanced-concepts/procedural_macros/01-derive-macro/my-derive/src/lib.rs @@ -1,6 +1,6 @@ use proc_macro::TokenStream; use quote::quote; -use syn::{parse_macro_input, DeriveInput, Data, Fields}; +use syn::{parse_macro_input, Data, DeriveInput, Fields}; /// Derive macro to implement a HelloWorld trait /// @@ -41,8 +41,8 @@ pub fn field_names_derive(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; - let fields = match ast.data { - Data::Struct(data_struct) => match data_struct.fields { + let fields = match &ast.data { + Data::Struct(data_struct) => match &data_struct.fields { Fields::Named(fields_named) => { let field_names: Vec<_> = fields_named .named @@ -57,7 +57,7 @@ pub fn field_names_derive(input: TokenStream) -> TokenStream { } pub fn field_count() -> usize { - #(stringify!(#field_names),)* .len() + Self::field_names().len() } } } @@ -89,22 +89,19 @@ pub fn enum_iter_derive(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; - let variants = match ast.data { + let variants = match &ast.data { Data::Enum(data_enum) => { let variant_idents: Vec<_> = data_enum .variants .iter() - .filter(|v| v.fields == Fields::Unit) + .filter(|v| matches!(v.fields, Fields::Unit)) .map(|v| &v.ident) .collect(); if variant_idents.is_empty() { - return syn::Error::new_spanned( - ast, - "EnumIter requires at least one unit variant", - ) - .to_compile_error() - .into(); + return syn::Error::new_spanned(ast, "EnumIter requires at least one unit variant") + .to_compile_error() + .into(); } let count = variant_idents.len(); @@ -142,8 +139,8 @@ pub fn custom_default_derive(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; - let fields = match ast.data { - Data::Struct(data_struct) => match data_struct.fields { + let fields = match &ast.data { + Data::Struct(data_struct) => match &data_struct.fields { Fields::Named(fields_named) => { let field_inits = fields_named.named.iter().map(|f| { let field_name = f.ident.as_ref().unwrap(); diff --git a/07-advanced-concepts/procedural_macros/02-attribute-macro/example/src/main.rs b/07-advanced-concepts/procedural_macros/02-attribute-macro/example/src/main.rs index 58aebb6..ce94ac8 100644 --- a/07-advanced-concepts/procedural_macros/02-attribute-macro/example/src/main.rs +++ b/07-advanced-concepts/procedural_macros/02-attribute-macro/example/src/main.rs @@ -1,4 +1,4 @@ -use my_attribute::{log_entry_exit, time_execution, retry, deprecated_fn}; +use my_attribute::{deprecated_fn, log_entry_exit, retry, time_execution}; use std::thread; use std::time::Duration; diff --git a/07-advanced-concepts/procedural_macros/02-attribute-macro/my-attribute/src/lib.rs b/07-advanced-concepts/procedural_macros/02-attribute-macro/my-attribute/src/lib.rs index 18a1f75..91a8051 100644 --- a/07-advanced-concepts/procedural_macros/02-attribute-macro/my-attribute/src/lib.rs +++ b/07-advanced-concepts/procedural_macros/02-attribute-macro/my-attribute/src/lib.rs @@ -1,6 +1,6 @@ use proc_macro::TokenStream; use quote::quote; -use syn::{parse_macro_input, ItemFn, AttributeArgs, NestedMeta, Meta, Lit}; +use syn::{parse_macro_input, punctuated::Punctuated, Expr, ItemFn, Lit, Meta, Token}; /// Attribute macro that logs function entry and exit /// @@ -81,7 +81,7 @@ pub fn time_execution(_attr: TokenStream, item: TokenStream) -> TokenStream { /// ``` #[proc_macro_attribute] pub fn retry(args: TokenStream, item: TokenStream) -> TokenStream { - let args = parse_macro_input!(args as AttributeArgs); + let args = parse_macro_input!(args with Punctuated::::parse_terminated); let input = parse_macro_input!(item as ItemFn); let mut times = 3; @@ -89,13 +89,15 @@ pub fn retry(args: TokenStream, item: TokenStream) -> TokenStream { // Parse arguments for arg in args { - if let NestedMeta::Meta(Meta::NameValue(nv)) = arg { + if let Meta::NameValue(nv) = arg { if nv.path.is_ident("times") { - if let Lit::Int(lit) = nv.lit { + if let Expr::Lit(expr) = nv.value { + let Lit::Int(lit) = expr.lit else { continue }; times = lit.base10_parse::().unwrap(); } } else if nv.path.is_ident("delay_ms") { - if let Lit::Int(lit) = nv.lit { + if let Expr::Lit(expr) = nv.value { + let Lit::Int(lit) = expr.lit else { continue }; delay_ms = lit.base10_parse::().unwrap(); } } @@ -152,7 +154,7 @@ pub fn retry(args: TokenStream, item: TokenStream) -> TokenStream { /// ``` #[proc_macro_attribute] pub fn deprecated_fn(args: TokenStream, item: TokenStream) -> TokenStream { - let args = parse_macro_input!(args as AttributeArgs); + let args = parse_macro_input!(args with Punctuated::::parse_terminated); let input = parse_macro_input!(item as ItemFn); let mut since = String::from("unknown"); @@ -160,20 +162,21 @@ pub fn deprecated_fn(args: TokenStream, item: TokenStream) -> TokenStream { // Parse arguments for arg in args { - if let NestedMeta::Meta(Meta::NameValue(nv)) = arg { + if let Meta::NameValue(nv) = arg { if nv.path.is_ident("since") { - if let Lit::Str(lit) = nv.lit { + if let Expr::Lit(expr) = nv.value { + let Lit::Str(lit) = expr.lit else { continue }; since = lit.value(); } } else if nv.path.is_ident("note") { - if let Lit::Str(lit) = nv.lit { + if let Expr::Lit(expr) = nv.value { + let Lit::Str(lit) = expr.lit else { continue }; note = lit.value(); } } } } - let fn_name = &input.sig.ident; let fn_block = &input.block; let fn_sig = &input.sig; let fn_vis = &input.vis; diff --git a/07-advanced-concepts/procedural_macros/03-builder-pattern/example/src/main.rs b/07-advanced-concepts/procedural_macros/03-builder-pattern/example/src/main.rs index 2168f74..d1938d5 100644 --- a/07-advanced-concepts/procedural_macros/03-builder-pattern/example/src/main.rs +++ b/07-advanced-concepts/procedural_macros/03-builder-pattern/example/src/main.rs @@ -58,7 +58,7 @@ fn main() { .email("alice@example.com".to_string()) .build() .unwrap(); - println!("User: {:?}\n", user); + println!("User: {} {} {}\n", user.id, user.name, user.email); // Example 2: With optional fields println!("=== 2. Builder with Optional Fields ==="); @@ -69,14 +69,20 @@ fn main() { .price(999.99) .build() .unwrap(); - println!("Product 1: {:?}", product1); + println!( + "Product 1: {} {} {:?} {:?}", + product1.id, product1.name, product1.description, product1.price + ); let product2 = Product::builder() .id(102) .name("Mouse".to_string()) .build() .unwrap(); - println!("Product 2 (minimal): {:?}\n", product2); + println!( + "Product 2: {} {} {:?} {:?}\n", + product2.id, product2.name, product2.description, product2.price + ); // Example 3: Configuration println!("=== 3. Server Configuration ==="); @@ -87,7 +93,10 @@ fn main() { .enable_logging(true) .build() .unwrap(); - println!("Server config: {:?}\n", config); + println!( + "Server config: {}:{} workers={:?} timeout={:?} logging={:?}\n", + config.host, config.port, config.workers, config.timeout_secs, config.enable_logging + ); // Example 4: Database connection println!("=== 4. Database Connection ==="); @@ -101,7 +110,16 @@ fn main() { .ssl(true) .build() .unwrap(); - println!("Database: {:?}\n", db_conn); + println!( + "Database: {}:{} / {} user={} password={:?} max_connections={:?} ssl={:?}\n", + db_conn.host, + db_conn.port, + db_conn.database, + db_conn.username, + db_conn.password, + db_conn.max_connections, + db_conn.ssl + ); // Example 5: Error handling - missing required field println!("=== 5. Error Handling ==="); diff --git a/07-advanced-concepts/procedural_macros/03-builder-pattern/my-builder/src/lib.rs b/07-advanced-concepts/procedural_macros/03-builder-pattern/my-builder/src/lib.rs index f70ad19..fa0186b 100644 --- a/07-advanced-concepts/procedural_macros/03-builder-pattern/my-builder/src/lib.rs +++ b/07-advanced-concepts/procedural_macros/03-builder-pattern/my-builder/src/lib.rs @@ -1,6 +1,6 @@ use proc_macro::TokenStream; -use quote::{quote, format_ident}; -use syn::{parse_macro_input, DeriveInput, Data, Fields, Type}; +use quote::{format_ident, quote}; +use syn::{parse_macro_input, Data, DeriveInput, Fields, Type}; /// Derive macro that generates a builder pattern implementation /// @@ -29,9 +29,9 @@ pub fn derive_builder(input: TokenStream) -> TokenStream { let name = &ast.ident; let builder_name = format_ident!("{}Builder", name); - let fields = match ast.data { - Data::Struct(data_struct) => match data_struct.fields { - Fields::Named(fields_named) => fields_named.named, + let fields = match &ast.data { + Data::Struct(data_struct) => match &data_struct.fields { + Fields::Named(fields_named) => &fields_named.named, _ => { return syn::Error::new_spanned(ast, "Builder only supports named fields") .to_compile_error() diff --git a/07-advanced-concepts/webassembly/01-hello-wasm/src/lib.rs b/07-advanced-concepts/webassembly/01-hello-wasm/src/lib.rs index d8d3187..114c769 100644 --- a/07-advanced-concepts/webassembly/01-hello-wasm/src/lib.rs +++ b/07-advanced-concepts/webassembly/01-hello-wasm/src/lib.rs @@ -31,13 +31,13 @@ pub fn is_prime(n: u32) -> bool { if n <= 3 { return true; } - if n % 2 == 0 || n % 3 == 0 { + if n.is_multiple_of(2) || n.is_multiple_of(3) { return false; } let mut i = 5; while i * i <= n { - if n % i == 0 || n % (i + 2) == 0 { + if n.is_multiple_of(i) || n.is_multiple_of(i + 2) { return false; } i += 6; diff --git a/07-advanced-concepts/webassembly/04-game-of-life/src/lib.rs b/07-advanced-concepts/webassembly/04-game-of-life/src/lib.rs index b10ecb9..3b21bc2 100644 --- a/07-advanced-concepts/webassembly/04-game-of-life/src/lib.rs +++ b/07-advanced-concepts/webassembly/04-game-of-life/src/lib.rs @@ -11,13 +11,7 @@ pub struct Universe { impl Universe { pub fn new(width: u32, height: u32) -> Universe { let cells = (0..width * height) - .map(|i| { - if i % 2 == 0 || i % 7 == 0 { - 1 - } else { - 0 - } - }) + .map(|i| if i % 2 == 0 || i % 7 == 0 { 1 } else { 0 }) .collect(); Universe { diff --git a/08-design-patterns/PATTERNS_SUMMARY.md b/08-design-patterns/PATTERNS_SUMMARY.md index 94e6aa5..e22b504 100644 --- a/08-design-patterns/PATTERNS_SUMMARY.md +++ b/08-design-patterns/PATTERNS_SUMMARY.md @@ -49,3 +49,5 @@ For any proposed pattern, ask: The [module README](README.md) links to the runnable code and C4-PlantUML design for every pattern. + +For a per-pattern list of counter-signals, read [WHEN_NOT_TO_USE.md](WHEN_NOT_TO_USE.md). The [RUST_NATIVE_PATTERNS.md](RUST_NATIVE_PATTERNS.md) guide covers designs that are often clearer than a direct Gang of Four translation. diff --git a/08-design-patterns/PATTERN_AUDIT.md b/08-design-patterns/PATTERN_AUDIT.md new file mode 100644 index 0000000..66c50eb --- /dev/null +++ b/08-design-patterns/PATTERN_AUDIT.md @@ -0,0 +1,19 @@ +# Pattern Audit Notes + +This is an idiomaticity audit of the runnable examples, not a claim that every pattern is the preferred Rust design. The programs are useful demonstrations of pattern participants; production code should select the smallest representation that makes the domain clear. + +| Area | Audit result | Practical guidance | +|---|---|---| +| Creational patterns | Examples correctly show construction choices, but factories and builders should not be automatic ceremony. | Prefer constructors, enums, and configuration values until runtime product selection or complex named construction is real. | +| Structural patterns | The examples demonstrate wrappers and delegation accurately. | Make wrappers earn their place with a policy boundary, compatibility boundary, or independent variation; do not wrap a direct call merely to match a catalog name. | +| Behavioural patterns | The examples correctly demonstrate dispatch and coordination. | Enums, iterator adapters, functions, and channels are often more direct Rust forms of the same behaviour. | +| Dynamic dispatch | Several examples use `Box` to make participants visible. | This is appropriate for runtime heterogeneity; prefer generics or enums when the set of implementations is known. | +| Shared state | Observer and proxy examples illustrate interior mutability and synchronization. | Treat `RefCell` as single-threaded runtime borrow checking and treat locks as part of the design, not as incidental plumbing. | +| Singleton documentation | The README includes older `static mut` and `unsafe` teaching snippets alongside modern lazy initialization. | Do not copy those snippets into application code. Prefer `std::sync::OnceLock` or `LazyLock`; explicit construction remains the default for dependencies. | +| Error handling | Most focused runnable examples use explicit results where transitions may fail. | Public APIs should return domain-relevant `Result` values and avoid panic-driven routine control flow. | + +## Review conclusion + +The module is suitable as a catalog of runnable demonstrations, provided readers use the selection guidance. The most important correction to a class-oriented interpretation is that a named GoF pattern is optional in Rust: an enum, a function, an iterator, a generic type, or explicit composition is often the final design. + +Read [WHEN_NOT_TO_USE.md](WHEN_NOT_TO_USE.md), [RUST_NATIVE_PATTERNS.md](RUST_NATIVE_PATTERNS.md), and [TRANSFER_GUIDE.md](TRANSFER_GUIDE.md) alongside the individual examples. diff --git a/08-design-patterns/README.md b/08-design-patterns/README.md index 668a17b..e0165af 100644 --- a/08-design-patterns/README.md +++ b/08-design-patterns/README.md @@ -99,4 +99,4 @@ Java-oriented comparison, see Saumil Patel's Compare the problem and participants first; do not translate Java classes into Rust types one for one. -See [PATTERNS_SUMMARY.md](PATTERNS_SUMMARY.md) for a compact selection guide. +See [PATTERNS_SUMMARY.md](PATTERNS_SUMMARY.md) for a compact selection guide, [WHEN_NOT_TO_USE.md](WHEN_NOT_TO_USE.md) for counter-signals, [RUST_NATIVE_PATTERNS.md](RUST_NATIVE_PATTERNS.md) for patterns that start with Rust's type system, and [TRANSFER_GUIDE.md](TRANSFER_GUIDE.md) before translating Java or C++ designs. diff --git a/08-design-patterns/RUST_NATIVE_PATTERNS.md b/08-design-patterns/RUST_NATIVE_PATTERNS.md new file mode 100644 index 0000000..ed79890 --- /dev/null +++ b/08-design-patterns/RUST_NATIVE_PATTERNS.md @@ -0,0 +1,35 @@ +# Rust-Native Design Patterns + +The GoF names remain useful, but Rust has tools that often express the same intent with fewer moving parts. These are not replacements in every case; they are the first alternatives worth checking. + +## Model a closed domain with enums + +Use an enum when all variants belong to the application and are known together. `match` keeps each case visible, lets the compiler check exhaustiveness, and commonly replaces class hierarchies, simple factories, visitors, and state objects. Add a trait object only when downstream code must introduce new implementations without editing the enum. + +## Make invalid values difficult to construct + +Use a newtype with a validating constructor for values such as account identifiers, bounded percentages, and parsed addresses. The type carries the invariant instead of asking every caller to remember it. For transitions whose order is central to safety, typestate can encode the permitted next operation in the type parameter; use it sparingly because it makes APIs more advanced. + +## Let ownership describe resources + +RAII is the default resource-management pattern in Rust. A value acquires a resource, its owner controls the lifetime, and `Drop` releases it when the value leaves scope. Prefer this model over manual `close` or `dispose` protocols. If cleanup can fail, provide an explicit `finish` or `shutdown` method and document what happens when it is skipped. + +## Represent fallibility in the type + +Use `Result` for expected failure and `Option` for meaningful absence. This makes error paths part of the signature and usually removes exception-style control flow. Add context at application boundaries, keep library error types specific enough for recovery, and avoid `unwrap` outside examples or invariants that are clearly explained. + +## Prefer static dispatch until runtime choice is required + +Generics and `impl Trait` give zero-cost abstraction when one concrete implementation is selected per call site. Use `dyn Trait` when a heterogeneous collection, plugin boundary, or runtime strategy choice is genuinely necessary. This distinction is often the Rust form of Strategy, Bridge, Decorator, and Factory. + +## Use iterators and adapters for data flow + +Iterator combinators express lazy transformations without a separate pipeline framework. Use `map`, `filter`, `filter_map`, `try_fold`, and `collect` when they reveal the transformation; use a `for` loop when names, branching, or early exits make it easier to read. Iterators commonly replace hand-written visitor and command-like traversal code. + +## Choose concurrency boundaries explicitly + +`std::sync::mpsc` channels, shared `Arc` ownership, and synchronization primitives solve different problems. Prefer message passing when one owner should serialize changes; prefer `Arc>` or `Arc>` only when shared mutable state is the actual model. In async code, do not hold a blocking lock across an `.await`; choose async-aware primitives when tasks must wait cooperatively. + +## Compose dependencies instead of locating them globally + +Construct application services at the edge and pass the narrow capability each component needs. A small trait can make a boundary testable, but a concrete reference is better when there is no alternative implementation. This is explicit composition, not a container pattern, and it keeps configuration and ownership visible. diff --git a/08-design-patterns/TRANSFER_GUIDE.md b/08-design-patterns/TRANSFER_GUIDE.md new file mode 100644 index 0000000..3089dc0 --- /dev/null +++ b/08-design-patterns/TRANSFER_GUIDE.md @@ -0,0 +1,45 @@ +# Moving Design Patterns from Java and C++ to Rust + +Translate the design pressure, not the class diagram. Rust's ownership, enums, traits, and zero-cost generics change which patterns are useful and how their costs appear. + +## Common Java transfers that go wrong + +### Rebuilding inheritance trees with trait objects + +Java interfaces often lead directly to `Box`. In Rust, start with an enum when the variants are closed, a generic when the implementation is chosen by the caller, and a trait object only for runtime heterogeneity or an extension boundary. Trait objects add object-safety limits, allocation or indirection in many designs, and less visible concrete behaviour. + +### Treating `Arc>` as ordinary object state + +`Arc>` is not a general substitute for Java references. It makes sharing and locking part of every access path. First decide who should own the data; then use a channel, immutable sharing with `Arc`, or a lock only when concurrent mutation is truly required. Never keep a `MutexGuard` across an `.await`. + +### Replacing exceptions with `unwrap` + +`unwrap` is not Rust's normal error-handling mechanism. Propagate with `?`, model recoverable cases with `Result`, and reserve `expect` for a documented invariant. A panic is appropriate for a bug or unrecoverable program state, not for routine invalid input or I/O failure. + +### Turning every service into a singleton + +Global service locators hide construction order, dependencies, and test configuration. Build the application graph at startup and pass dependencies explicitly. Use `OnceLock` or `LazyLock` only for process-wide immutable or carefully synchronized state that is genuinely global. + +## Common C++ transfers that go wrong + +### Porting raw ownership protocols + +Do not reproduce `new`, `delete`, nullable owning pointers, or manual reference counting. Prefer owned values and borrowing; use `Box` for a value with a stable heap address or recursive size, `Rc` for single-threaded shared ownership, and `Arc` for thread-safe shared ownership. Shared ownership can create cycles, so use `Weak` for back-references. + +### Using inheritance for runtime variation + +Rust has no implementation inheritance. Use composition for shared data and traits for shared behaviour. Default trait methods can share small pieces of behaviour, but a trait should describe a capability rather than become a base class with hidden state. + +### Copying move semantics without checking the API contract + +Moves in Rust are the default transfer of ownership, not an optimization hint. A function that accepts `T` takes ownership; `&T` borrows read-only access; `&mut T` borrows exclusive mutable access. Design these choices into public signatures so callers can predict whether a value remains usable. + +## Translation checklist + +1. What owns each resource and for how long? +2. Is the variant set open or closed? +3. Does the caller need runtime choice, or would a generic or enum be clearer? +4. How does a failure reach the caller? +5. Does the design need shared mutation, or can one owner coordinate changes? + +See [RUST_NATIVE_PATTERNS.md](RUST_NATIVE_PATTERNS.md) for the Rust-first alternatives and [WHEN_NOT_TO_USE.md](WHEN_NOT_TO_USE.md) for counter-signals for every example in this module. diff --git a/08-design-patterns/WHEN_NOT_TO_USE.md b/08-design-patterns/WHEN_NOT_TO_USE.md new file mode 100644 index 0000000..c530824 --- /dev/null +++ b/08-design-patterns/WHEN_NOT_TO_USE.md @@ -0,0 +1,32 @@ +# When Not to Use a Pattern + +A pattern earns its complexity only when it removes a real constraint. This guide is deliberately conservative: start with a direct Rust representation, then introduce a pattern when the direct form begins to hide the important change. + +| Pattern | Avoid it when | Prefer | +|---|---|---| +| Abstract Factory | Product families are fixed and small. | An enum or constructors on the concrete types. | +| Builder | Construction has only a few required arguments. | A constructor, a struct literal inside the defining crate, or a configuration struct. | +| Factory and Factory Method | Selection is closed and known at compile time. | An enum plus `match`; use a factory for plugins or runtime choice. | +| Prototype | Copying configuration is cheaper and clearer than preserving identity. | `Clone`, a constructor, or an explicit configuration value. | +| Singleton | A caller can supply the dependency or different tests need different instances. | Explicit dependency injection through function arguments or a context value. | +| Adapter | The two APIs are both under your control. | Rename or redesign the original interface rather than preserving an accidental boundary. | +| Bridge | Only one side is expected to vary. | A generic type or a concrete field. | +| Composite | A tree has different operations for leaves and branches. | A recursive enum with separate `match` arms. | +| Decorator | The layer count is fixed and each layer needs unrelated configuration. | One concrete type or a builder that assembles the final value. | +| Facade | It merely forwards one call. | Call the subsystem directly. | +| Flyweight | Sharing introduces lifetime, synchronization, or cache invalidation costs larger than the saved allocation. | Own the small value, or intern only measured hot data. | +| Proxy | The wrapper changes neither policy nor observable behaviour. | Use the subject directly. | +| Chain of Responsibility | Every request must follow the same known path. | A straightforward function pipeline or `match`. | +| Command | Work is executed immediately and never stored, retried, or undone. | A function or closure. | +| Iterator | A collection API is simpler and no lazy traversal is needed. | Return a collection or expose a slice. | +| Mediator | A coordinator becomes the only place that understands every component. | Direct collaboration with narrow interfaces, or events with clear ownership. | +| Memento | Snapshots are large, frequent, or cannot be restored safely. | Record domain events, use a transaction, or make an explicit copy at a boundary. | +| Observer | Ordering, failure, or backpressure matters to the producer. | A request/response API, a channel with a stated policy, or an async stream. | +| State | States are few and transitions are local. | An enum and `match`; consider typestate only when compile-time transition guarantees justify it. | +| Strategy | Algorithms do not need runtime replacement. | A generic parameter, enum, or ordinary helper function. | +| Template Method | Inheritance-shaped hooks obscure a short workflow. | Compose functions or use a trait only for a genuine extension point. | +| Visitor | Both operations and element variants change often. | Keep operations near the enum and use `match`; visitor is strongest when variants are stable. | + +## A quick decision check + +Before adding indirection, write the direct version and name the expected change. If the change is speculative, keep the direct version. If the change is real, choose the smallest abstraction that makes ownership, failure, and control flow easier to see. diff --git a/08-design-patterns/creational/singleton/README.md b/08-design-patterns/creational/singleton/README.md index 858f0e7..bcf9946 100644 --- a/08-design-patterns/creational/singleton/README.md +++ b/08-design-patterns/creational/singleton/README.md @@ -44,30 +44,24 @@ fn main() { } ``` -### Using `std::sync::Once` for Manual Control +### Using `std::sync::OnceLock` for Initialization Parameters ```rust -use std::sync::Once; +use std::sync::OnceLock; pub struct Config { db_url: String, api_key: String, } -static mut CONFIG: Option = None; -static INIT: Once = Once::new(); +static CONFIG: OnceLock = OnceLock::new(); impl Config { - pub fn get() -> &'static Config { - unsafe { - INIT.call_once(|| { - CONFIG = Some(Config { - db_url: "postgres://localhost".to_string(), - api_key: "secret-key".to_string(), - }); - }); - CONFIG.as_ref().unwrap() - } + pub fn get_or_init() -> &'static Config { + CONFIG.get_or_init(|| Config { + db_url: "postgres://localhost".to_string(), + api_key: "secret-key".to_string(), + }) } pub fn db_url(&self) -> &str { @@ -81,7 +75,7 @@ impl Config { // Usage fn main() { - let config = Config::get(); + let config = Config::get_or_init(); println!("Database: {}", config.db_url()); } ``` @@ -131,8 +125,7 @@ fn main() { ### Thread-Safe Singleton with Initialization Function ```rust -use std::sync::{Arc, Mutex, Once}; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; pub struct ApplicationState { initialized: bool, @@ -141,29 +134,18 @@ pub struct ApplicationState { pub struct AppStateManager; -static mut APP_STATE: Option>> = None; -static INIT: Once = Once::new(); -static INIT_FLAG: AtomicBool = AtomicBool::new(false); +static APP_STATE: OnceLock>> = OnceLock::new(); impl AppStateManager { pub fn initialize(initial_data: Vec) -> Result<(), String> { - if INIT_FLAG.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).is_err() { - return Err("Already initialized".to_string()); - } - - unsafe { - INIT.call_once(|| { - APP_STATE = Some(Arc::new(Mutex::new(ApplicationState { - initialized: true, - data: initial_data, - }))); - }); - } - Ok(()) + APP_STATE.set(Arc::new(Mutex::new(ApplicationState { + initialized: true, + data: initial_data, + }))).map_err(|_| "Already initialized".to_string()) } pub fn get() -> Option>> { - unsafe { APP_STATE.clone() } + APP_STATE.get().cloned() } } @@ -229,27 +211,22 @@ pub fn increment() { ### Pattern 4: Singleton with Initialization Parameters ```rust -use std::sync::Once; +use std::sync::OnceLock; pub struct Config { environment: String, } -static mut CONFIG: Option = None; -static INIT: Once = Once::new(); +static CONFIG: OnceLock = OnceLock::new(); -pub fn init_config(env: &str) { - unsafe { - INIT.call_once(|| { - CONFIG = Some(Config { - environment: env.to_string(), - }); - }); - } +pub fn init_config(env: &str) -> Result<(), Config> { + CONFIG.set(Config { + environment: env.to_string(), + }) } pub fn get_config() -> &'static Config { - unsafe { CONFIG.as_ref().expect("Config not initialized") } + CONFIG.get().expect("config not initialized") } ``` diff --git a/10-real-world-rust/concurrency_intro/metadata.json b/10-real-world-rust/concurrency_intro/metadata.json new file mode 100644 index 0000000..36f1f91 --- /dev/null +++ b/10-real-world-rust/concurrency_intro/metadata.json @@ -0,0 +1,27 @@ +{ + "$schema": "../../schemas/topic-metadata-v1.schema.json", + "schema_version": 1, + "id": "10-concurrency", + "title": "Concurrency Introduction", + "status": "planned", + "level": "advanced", + "estimated_minutes": 120, + "prerequisites": ["01-ownership", "06-traits"], + "concepts": ["threads", "message-passing", "shared-state", "arc", "mutex", "data-races"], + "tracks": ["core", "java", "python", "cpp", "go"], + "learning_objectives": [ + "Explain how ownership prevents data races across threads.", + "Choose between message passing and shared state for a concurrency problem.", + "Use Arc and synchronization primitives to share mutable state safely.", + "Distinguish workloads suited to threads, async tasks, or data parallelism." + ], + "website": { + "published": false, + "order": null + }, + "validation": { + "content_rubric": "pending", + "examples": "pending", + "exercises": "pending" + } +} diff --git a/11-language-specific-tracks/CPP_TRACK/CANONICAL_RUST_LINKS.md b/11-language-specific-tracks/CPP_TRACK/CANONICAL_RUST_LINKS.md new file mode 100644 index 0000000..fe28153 --- /dev/null +++ b/11-language-specific-tracks/CPP_TRACK/CANONICAL_RUST_LINKS.md @@ -0,0 +1,18 @@ +# Canonical Rust Lessons for C++ Developers + +Rust and modern C++ share many goals, especially deterministic cleanup and systems-level performance. The comparisons here identify useful starting points; they are not source-to-source translations and should not be used to infer identical guarantees. + +| C++ starting point | Rust concept to learn | Important difference | Canonical lesson | +|---|---|---|---| +| Object lifetime and RAII | Ownership, moves, and scope-based cleanup | Both use deterministic cleanup, but Rust makes aliasing and mutation rules part of the type-checked program. | [Ownership](../../01-core-fundamentals/ownership/README.md) | +| Raw pointers and references | References and borrowing | Rust references are not nullable and must satisfy borrowing rules; raw pointers are a separate unsafe facility. | [Ownership](../../01-core-fundamentals/ownership/README.md) | +| `std::unique_ptr` and move operations | Owned values and moves | An ordinary Rust value is already an owning value; `Box` is not the default spelling for every owner. | [Ownership](../../01-core-fundamentals/ownership/README.md) | +| `std::shared_ptr` | `Rc` and `Arc` | Shared ownership is explicit and cannot by itself provide mutable access; it is not a general replacement for ordinary ownership. | [Ownership](../../01-core-fundamentals/ownership/README.md) | +| Templates and concepts | Generics and trait bounds | Rust monomorphizes many generic calls, but trait coherence, specialization, and overload rules differ from C++. | [Generics](../../06-intermediate-rust/generics/README.md) and [traits](../../06-intermediate-rust/traits_and_polymorphism/README.md) | +| Class inheritance and virtual functions | Structs, enums, traits, and trait objects | Traits describe capabilities, not a shared base-object layout or inherited fields. | [Traits and polymorphism](../../06-intermediate-rust/traits_and_polymorphism/README.md) | +| Exceptions and error codes | `Result` | Expected failure is normally visible in the return type; panic is not an exception-handling mechanism. | [Result and recoverable errors](../../02-standard-library/error_handling_basics/README.md) | +| STL algorithms and ranges | Iterators and collection APIs | Iterator methods express whether values are borrowed, mutably borrowed, or consumed. | [Iterator patterns](../../02-standard-library/iterator_patterns/README.md) and [collections](../../02-standard-library/collections/README.md) | +| `std::thread`, locks, and atomics | `Send`, `Sync`, and synchronization | Rust still has locks and atomics, but invalid cross-thread ownership is rejected before execution. | [Concurrency introduction](../../10-real-world-rust/concurrency_intro/README.md) | +| CMake and package managers | Cargo packages and tooling | Cargo’s manifest, workspace, build-script, and lockfile model differs from CMake targets and external package managers. | [Tooling and quality](../../03-tooling-and-quality/README.md) | + +The first useful goal is not to recreate a C++ architecture in Rust. Learn to let ownership, enums, and explicit error types choose a simpler shape. diff --git a/11-language-specific-tracks/CPP_TRACK/MVP_CHECKS.md b/11-language-specific-tracks/CPP_TRACK/MVP_CHECKS.md new file mode 100644 index 0000000..72decaa --- /dev/null +++ b/11-language-specific-tracks/CPP_TRACK/MVP_CHECKS.md @@ -0,0 +1,14 @@ +# C++-to-Rust Migration Checks + +These prompts distinguish concepts that look familiar from guarantees that are actually different. Use the linked canonical lessons for implementation practice. + +| Focus | C++ mental model | Rust mental model | Common mistake to avoid | Challenge | +|---|---|---|---|---| +| Ownership | RAII is a convention implemented through destructors and resource-owning types. | Ownership is the default relationship for values and determines moves and cleanup. | Wrapping every value in `Box` or a reference-counted pointer. | Explain why a plain `String` owns its allocation and when `Box` is genuinely useful. | +| References | References and pointers have broad expressive power, including aliases that may be mutated. | `&T` allows shared reading; `&mut T` grants exclusive access for a bounded lifetime. | Treating a Rust reference as a nullable pointer or bypassing a borrow error with a clone. | Show why two mutable borrows of the same vector overlap incorrectly, then shorten one borrow without cloning. | +| Polymorphism | Inheritance and virtual methods often combine state reuse and dynamic dispatch. | Traits, generic bounds, trait objects, and enums solve separate problems. | Building a base-class hierarchy with trait objects before considering an enum or generic function. | Choose an enum, generic trait bound, or trait object for a fixed set of runtime-selected commands and justify it. | +| Errors | Exceptions may leave ordinary function signatures unchanged. | `Result` advertises recoverable failure at the call boundary. | Using `panic!` for malformed user input. | Give a parser signature with a useful error type and describe what `?` returns to its caller. | +| Iteration | Algorithms operate over iterators, ranges, and callable objects. | Iterators also encode whether the source is borrowed or consumed. | Translating a range algorithm without deciding who owns the input afterwards. | For `Vec`, select the iterator form that retains the vector and the one that transfers its strings to a new collection. | +| Concurrency | A data race can compile and become undefined behavior. | Types must satisfy `Send` and `Sync` before data crosses or is shared between threads. | Assuming the compiler prevents deadlocks or makes mutex design unnecessary. | Contrast a channel-based worker handoff with an `Arc>` design and name the trade-off each makes. | + +If a solution relies on an unsafe escape hatch, state the safety contract first. Unsafe code changes who proves the invariant; it does not suspend the invariant. diff --git a/11-language-specific-tracks/CPP_TRACK/README.md b/11-language-specific-tracks/CPP_TRACK/README.md index 4cd4eb3..cbacfe1 100644 --- a/11-language-specific-tracks/CPP_TRACK/README.md +++ b/11-language-specific-tracks/CPP_TRACK/README.md @@ -155,6 +155,8 @@ The compiler *prevents* data races. Not at runtime—at compile time. - **CHEAT_SHEET.md** - Quick C/C++ → Rust lookup - **GOTCHAS.md** - Surprises for C/C++ developers - **TIPS_AND_TRICKS.md** - Productivity shortcuts + - **CANONICAL_RUST_LINKS.md** - Canonical runnable Rust lessons for each comparison + - **MVP_CHECKS.md** - Short migration challenges that test the mental-model shift ## Learning timeline diff --git a/11-language-specific-tracks/CROSS_LANGUAGE_COMPARISON.md b/11-language-specific-tracks/CROSS_LANGUAGE_COMPARISON.md new file mode 100644 index 0000000..5f0e6c0 --- /dev/null +++ b/11-language-specific-tracks/CROSS_LANGUAGE_COMPARISON.md @@ -0,0 +1,27 @@ +# Cross-Language Rust Transition Index + +Choose a track for the language that has most shaped your instincts, then use the canonical Rust lessons for the underlying instruction. This index compares mental models; a cell is not a promise of equivalent syntax, runtime behavior, or library APIs. + +| Area | Java | Python | Go | C++ | Canonical Rust lesson | +|---|---|---|---|---|---| +| Memory management | Garbage-collected object reachability | Reference counting and garbage collection | Garbage collection | RAII, pointers, and smart pointers | [Ownership](../01-core-fundamentals/ownership/README.md) | +| Aliasing and mutation | References plus API or lock discipline | Mutable object aliases are common | Pointers and shared state are conventional | References and pointers have broad expressive power | [Ownership](../01-core-fundamentals/ownership/README.md) | +| Absent values | `null` and `Optional` | `None` | `nil` | Null pointers or optional-like libraries | [Result and recoverable errors](../02-standard-library/error_handling_basics/README.md) | +| Recoverable errors | Checked and unchecked exceptions | Exceptions | Explicit `error` values | Exceptions, error codes, or expected-like types | [Result and recoverable errors](../02-standard-library/error_handling_basics/README.md) | +| Polymorphism | Classes, interfaces, and inheritance | Duck typing and protocols | Structural interfaces | Inheritance, templates, and virtual functions | [Traits and polymorphism](../06-intermediate-rust/traits_and_polymorphism/README.md) | +| Collection pipelines | Streams | Comprehensions and generators | `range` loops | STL algorithms and ranges | [Iterator patterns](../02-standard-library/iterator_patterns/README.md) | +| Concurrent work | Executors, locks, and futures | Threads, processes, and `asyncio` | Goroutines and channels | Threads, locks, and atomics | [Concurrency introduction](../10-real-world-rust/concurrency_intro/README.md) and [advanced async](../07-advanced-concepts/advanced_async/README.md) | +| Build and dependencies | Maven or Gradle | `pip` and virtual environments | Go modules | CMake and package managers | [Tooling and quality](../03-tooling-and-quality/README.md) | + +## Pick the right starting track + +| Your strongest background | Track | First comparison | Migration checks | +|---|---|---|---| +| Java or JVM frameworks | [Java track](JAVA_TRACK/README.md) | [Canonical links](JAVA_TRACK/CANONICAL_RUST_LINKS.md) | [Java migration checks](JAVA_TRACK/MVP_CHECKS.md) | +| Python applications, scripts, or data work | [Python track](PYTHON_TRACK/README.md) | [Canonical links](PYTHON_TRACK/CANONICAL_RUST_LINKS.md) | [Python migration checks](PYTHON_TRACK/MVP_CHECKS.md) | +| Go services and concurrent programs | [Go track](GO_TRACK/README.md) | [Canonical links](GO_TRACK/CANONICAL_RUST_LINKS.md) | [Go migration checks](GO_TRACK/MVP_CHECKS.md) | +| C or C++ systems programming | [C++ track](CPP_TRACK/README.md) | [Canonical links](CPP_TRACK/CANONICAL_RUST_LINKS.md) | [C++ migration checks](CPP_TRACK/MVP_CHECKS.md) | + +## The common shift + +Every track reaches the same central Rust questions: who owns this value, who may borrow it now, what failure is expected, and which execution boundary is responsible for this work? Begin there even if a familiar library or framework appears to offer a direct translation. diff --git a/11-language-specific-tracks/GO_TRACK/CANONICAL_RUST_LINKS.md b/11-language-specific-tracks/GO_TRACK/CANONICAL_RUST_LINKS.md new file mode 100644 index 0000000..2c72ac8 --- /dev/null +++ b/11-language-specific-tracks/GO_TRACK/CANONICAL_RUST_LINKS.md @@ -0,0 +1,17 @@ +# Canonical Rust Lessons for Go Developers + +Go and Rust are both practical systems languages, but they make different choices about memory management, interfaces, and concurrency. These mappings point to the canonical Rust lessons; they are not one-for-one implementation recipes. + +| Go starting point | Rust concept to learn | Important difference | Canonical lesson | +|---|---|---|---| +| Garbage collection | Ownership, moves, and borrowing | Rust determines validity and cleanup from ownership rather than tracing reachable objects. | [Ownership](../../01-core-fundamentals/ownership/README.md) | +| Pointers and address-taking | Shared and mutable references | A Rust mutable reference must be exclusive; passing a pointer in Go does not carry that rule. | [Ownership](../../01-core-fundamentals/ownership/README.md) | +| `nil` pointers, maps, slices, and interfaces | `Option` and explicit initialization | `Option` represents expected absence; it is not merely a differently spelled `nil`. | [Result and recoverable errors](../../02-standard-library/error_handling_basics/README.md) | +| `error` return values | `Result` and `?` | Both make failure a value, but Rust encodes success and failure together in an enum that must be handled. | [Result and recoverable errors](../../02-standard-library/error_handling_basics/README.md) | +| Implicit interfaces | Traits and generic bounds | Go types satisfy interfaces structurally; Rust trait implementations are explicit and bounds are checked statically. | [Traits and polymorphism](../../06-intermediate-rust/traits_and_polymorphism/README.md) | +| Slices, maps, and `range` | Collections and iterator adapters | Rust collection APIs expose borrowing and ownership, so iteration has a different effect on later use. | [Collections](../../02-standard-library/collections/README.md) and [iterator patterns](../../02-standard-library/iterator_patterns/README.md) | +| `defer` | Scope-based cleanup and `Drop` | Both make cleanup easier to write, but Rust resource cleanup follows ownership and scope rather than a deferred call list. | [Ownership](../../01-core-fundamentals/ownership/README.md) | +| Goroutines and channels | Threads, channels, futures, and async runtimes | A Rust future is not a goroutine: it needs a runtime to poll it, and blocking must be designed deliberately. | [Concurrency introduction](../../10-real-world-rust/concurrency_intro/README.md) and [advanced async](../../07-advanced-concepts/advanced_async/README.md) | +| `go test`, modules, and tooling | Cargo packages, tests, and quality checks | Cargo has a different manifest and lockfile model, even where commands look familiar. | [Tooling and quality](../../03-tooling-and-quality/README.md) | + +Learn ownership before treating `Arc>` as the equivalent of passing pointers between goroutines. The compiler’s restrictions are intended to change the design boundary, not decorate the same shared-state design. diff --git a/11-language-specific-tracks/GO_TRACK/MVP_CHECKS.md b/11-language-specific-tracks/GO_TRACK/MVP_CHECKS.md new file mode 100644 index 0000000..fe595ae --- /dev/null +++ b/11-language-specific-tracks/GO_TRACK/MVP_CHECKS.md @@ -0,0 +1,14 @@ +# Go-to-Rust Migration Checks + +Use these short prompts to test the conceptual changes behind the syntax. The canonical lessons linked from [CANONICAL_RUST_LINKS.md](CANONICAL_RUST_LINKS.md) provide the runnable practice. + +| Focus | Go mental model | Rust mental model | Common mistake to avoid | Challenge | +|---|---|---|---|---| +| Object lifetime | The garbage collector keeps a reachable value alive. | A value is dropped when its owner goes out of scope unless ownership has moved elsewhere. | Keeping every value behind `Arc` because it feels safer than an owner. | Explain why assigning a `String` to another variable moves it and show when borrowing is the better function boundary. | +| Interface satisfaction | A type implements an interface by having matching methods. | A type explicitly implements a trait, and a function states its trait bounds. | Expecting a method with the right name to satisfy a Rust trait automatically. | Define a small trait for a dependency and state when a generic parameter is preferable to `dyn Trait`. | +| Absence and failure | `nil` and `error` are conventional return values. | `Option` and `Result` make the two cases distinct in the signature. | Using `unwrap()` where an error or absence comes from ordinary input. | Choose `Option` or `Result` for a missing configuration key and explain the caller’s handling path. | +| Iteration | `range` is a convenient default over collections. | `iter`, `iter_mut`, and `into_iter` describe different ownership actions. | Consuming a collection with `into_iter` before a later use. | For `Vec`, choose the correct iterator to print strings and then reuse the vector. | +| Concurrency | A goroutine can be started cheaply and channels coordinate it. | Rust threads and tasks must satisfy ownership rules; async futures are driven by a runtime. | Calling a blocking operation inside an async task because goroutines do not impose the same boundary. | Describe when a channel is clearer than a mutex and why spawning an async future does not itself prove it will run. | +| Cleanup | `defer` records cleanup near resource acquisition. | Drop-based cleanup happens as ownership leaves scope. | Assuming a destructor can safely borrow values that have already been dropped. | Sketch a file-processing scope and explain when its resource cleanup occurs, including on an early `?` return. | + +The intended answer is a design explanation, not a translation of Go syntax. If the result is only a keyword substitution, revisit the ownership or runtime difference. diff --git a/11-language-specific-tracks/GO_TRACK/README.md b/11-language-specific-tracks/GO_TRACK/README.md index bc8d603..033a60f 100644 --- a/11-language-specific-tracks/GO_TRACK/README.md +++ b/11-language-specific-tracks/GO_TRACK/README.md @@ -62,11 +62,8 @@ This track shows you how to think in Rust when you're coming from Go. - Service Discovery (async + networking) 4. **Reference the guides**: - - **DESIGN_PATTERNS_GUIDE.md** - Interface patterns, concurrency patterns - - **ANTI_PATTERNS.md** - Common Go developer mistakes - - **CHEAT_SHEET.md** - Quick Go → Rust lookup - - **GOTCHAS.md** - Surprises for Go developers - - **TIPS_AND_TRICKS.md** - Productivity shortcuts + - **CANONICAL_RUST_LINKS.md** - Canonical runnable Rust lessons for each comparison + - **MVP_CHECKS.md** - Short migration challenges that test the mental-model shift ## Learning timeline diff --git a/11-language-specific-tracks/JAVA_TRACK/CANONICAL_RUST_LINKS.md b/11-language-specific-tracks/JAVA_TRACK/CANONICAL_RUST_LINKS.md new file mode 100644 index 0000000..2b2a9de --- /dev/null +++ b/11-language-specific-tracks/JAVA_TRACK/CANONICAL_RUST_LINKS.md @@ -0,0 +1,17 @@ +# Canonical Rust Lessons for Java Developers + +This track explains the Java-to-Rust mental-model shift. Use the links below for the canonical Rust instruction, runnable examples, and exercises; this guide does not replace those lessons. + +| Java starting point | Rust concept to learn | Canonical lesson | +|---|---|---| +| Garbage collection and object references | Ownership, moves, and borrowing | [Ownership](../../01-core-fundamentals/ownership/README.md) | +| Interfaces and inheritance | Traits, composition, and static or dynamic dispatch | [Traits and polymorphism](../../06-intermediate-rust/traits_and_polymorphism/README.md) | +| `null` and `Optional` | `Option` and explicit absence | [Result and recoverable errors](../../02-standard-library/error_handling_basics/README.md) | +| Checked and unchecked exceptions | `Result`, `match`, and `?` | [Result and recoverable errors](../../02-standard-library/error_handling_basics/README.md) | +| Collections and streams | Collection ownership and iterators | [Collections](../../02-standard-library/collections/README.md) and [iterator patterns](../../02-standard-library/iterator_patterns/README.md) | +| `synchronized`, executors, and thread pools | Ownership-aware concurrency | [Concurrency introduction](../../10-real-world-rust/concurrency_intro/README.md) | +| `CompletableFuture` and virtual-thread mental models | Futures, tasks, and async boundaries | [Advanced async overview](../../07-advanced-concepts/advanced_async/README.md) | +| Maven or Gradle | Cargo commands, project layout, and quality tooling | [Tooling and quality](../../03-tooling-and-quality/README.md) | +| Framework-managed dependency injection | Explicit composition with structs and traits | [Intermediate Rust](../../06-intermediate-rust/README.md) | + +Treat these as comparisons, not one-to-one translations. Rust’s ownership model and type system often change the shape of the program, not just its syntax. diff --git a/11-language-specific-tracks/JAVA_TRACK/MVP_CHECKS.md b/11-language-specific-tracks/JAVA_TRACK/MVP_CHECKS.md new file mode 100644 index 0000000..c6eb5d9 --- /dev/null +++ b/11-language-specific-tracks/JAVA_TRACK/MVP_CHECKS.md @@ -0,0 +1,18 @@ +# Java-to-Rust Migration Checks + +Use these short checks after reading the comparison material. They verify a mental-model shift; they are not a replacement for the runnable lessons linked in [CANONICAL_RUST_LINKS.md](CANONICAL_RUST_LINKS.md). + +| Focus | Java mental model | Rust mental model | Difference to notice | Common mistake to avoid | Check yourself | Canonical lesson | +|---|---|---|---|---|---|---| +| Garbage collection and references | Objects may have many references; the garbage collector eventually reclaims unreachable objects. | A value has an owner, and a move, borrow, or shared owner must be explicit. | Rust determines validity from ownership and borrowing, rather than tracing reachability. | Treating a `String` assignment as another reference to the same value. | Explain why `let second = first;` prevents a later use of `first` when `first` is a `String`, and name two ways to keep both values usable. | [Ownership](../../01-core-fundamentals/ownership/README.md) | +| Borrowing and mutation | Any reference may be used to read or mutate an object when the API allows it. | `&T` shares read access and `&mut T` grants exclusive write access for a limited scope. | Exclusivity is checked before the program runs, not coordinated by convention. | Adding `clone()` before considering a shorter borrow or a different API boundary. | Sketch a function that changes a `String` without taking ownership, then explain why two simultaneous mutable borrows are rejected. | [Ownership](../../01-core-fundamentals/ownership/README.md) | +| Classes, interfaces, and inheritance | Classes combine state and behavior; interfaces and inheritance often provide polymorphism. | Structs hold state, enums model alternatives, and traits describe capabilities. | Traits do not create a shared object layout or inherited implementation state. | Rebuilding a class hierarchy with `Box` before deciding whether a generic or enum fits. | Choose between an enum, a generic trait bound, and a trait object for a payment method chosen from a fixed set at runtime. State why. | [Traits and polymorphism](../../06-intermediate-rust/traits_and_polymorphism/README.md) | +| `null` and `Optional` | A reference can be `null`; `Optional` is used where absence is made explicit. | `Option` makes absence part of the type and is handled with matching or combinators. | The absence case is visible in the function signature and must be considered at use sites. | Calling `unwrap()` where absent data is normal input. | Write the return type for a lookup that may not find a user, then describe how the caller should handle both outcomes. | [Result and recoverable errors](../../02-standard-library/error_handling_basics/README.md) | +| Exceptions and `Result` | Failure may be represented by checked or unchecked exceptions that change control flow. | Recoverable failure is returned as a value, usually `Result`, and `?` propagates it explicitly. | Rust callers can see failure in the return type; panic is not a substitute for expected errors. | Translating every `catch` block into `unwrap()`. | Convert a Java file-reading method that throws `IOException` into a Rust signature, then explain what `?` does to the error. | [Result and recoverable errors](../../02-standard-library/error_handling_basics/README.md) | +| Streams and iterators | A stream pipeline processes collection elements, often without exposing ownership details. | Iterators may consume values, borrow them, or yield mutable references. | The iterator method selected changes what remains usable after the pipeline. | Reaching for indexing or cloning when `iter`, `iter_mut`, or `into_iter` expresses the intent. | For a `Vec`, choose the iterator form that prints values without consuming the vector and the one that transfers the strings into a new collection. | [Collections](../../02-standard-library/collections/README.md) and [iterator patterns](../../02-standard-library/iterator_patterns/README.md) | +| `synchronized`, executors, and thread pools | Shared mutable state is commonly guarded with `synchronized`, locks, or concurrent collections. | Thread transfer and sharing require types that satisfy `Send` and `Sync`; synchronization primitives still protect shared mutation. | Rust prevents many invalid sharing arrangements at compile time but does not remove the need to design for contention and deadlocks. | Assuming `Arc>` is the default answer to every concurrent design. | Describe when a channel is clearer than a shared `Mutex`, and name the wrapper commonly used when several threads own the same value. | [Concurrency introduction](../../10-real-world-rust/concurrency_intro/README.md) | +| `CompletableFuture` and virtual threads | Futures and lightweight threads express work that completes later while an executor schedules it. | Futures are inert until polled by a runtime; `async` code should avoid blocking its executor threads. | Rust async is a cooperative execution model, not a direct replacement for either Java abstraction. | Calling a blocking operation inside an async task without moving it to an appropriate blocking context. | Explain why creating a Rust future does not necessarily start work, and identify the boundary where a blocking database client belongs. | [Advanced async overview](../../07-advanced-concepts/advanced_async/README.md) | +| Maven and Gradle | A build tool resolves dependencies, runs tests, and organizes project tasks. | Cargo defines packages and dependencies and provides a consistent command-line workflow. | Cargo manifests describe a package directly; its conventions differ from Maven coordinates and Gradle build scripts. | Treating `Cargo.lock` as a hand-maintained manifest or adding dependencies before checking whether the standard library fits. | Name the Cargo command for a test run and the two files that distinguish package configuration from resolved dependency versions. | [Tooling and quality](../../03-tooling-and-quality/README.md) | +| Dependency injection and composition | A framework often constructs an object graph and supplies collaborators through containers and annotations. | Constructors, structs, traits, and explicit wiring make dependencies visible at the composition root. | Rust has DI libraries, but ordinary explicit composition is usually the simplest starting point. | Hiding every dependency behind a trait object or global service locator. | Design a `Service` that depends on a repository: show which dependency should be a field, where it is constructed, and when a trait bound is justified for testing or substitution. | [Intermediate Rust](../../06-intermediate-rust/README.md) | + +If an answer feels like a syntax substitution, return to the comparison documents and identify the ownership, error, or execution-model difference first. That distinction is the point of the track. diff --git a/11-language-specific-tracks/JAVA_TRACK/README.md b/11-language-specific-tracks/JAVA_TRACK/README.md index cd945ab..3252385 100644 --- a/11-language-specific-tracks/JAVA_TRACK/README.md +++ b/11-language-specific-tracks/JAVA_TRACK/README.md @@ -74,6 +74,10 @@ I've organized this track to build on what you already know: - **GOTCHAS.md** - Things that will trip you up - **TIPS_AND_TRICKS.md** - Productivity shortcuts I learned the hard way +5. **Use CANONICAL_RUST_LINKS.md** - Follow the canonical Rust lessons for runnable examples and exercises instead of treating this comparison track as a second curriculum. + +6. **Work through MVP_CHECKS.md** - Use the short migration checks to confirm the Java-to-Rust mental-model shifts before moving on. + ## A realistic timeline Based on my experience and talking to other Java developers who've made the switch: diff --git a/11-language-specific-tracks/PYTHON_TRACK/CANONICAL_RUST_LINKS.md b/11-language-specific-tracks/PYTHON_TRACK/CANONICAL_RUST_LINKS.md new file mode 100644 index 0000000..c4e935b --- /dev/null +++ b/11-language-specific-tracks/PYTHON_TRACK/CANONICAL_RUST_LINKS.md @@ -0,0 +1,18 @@ +# Canonical Rust Lessons for Python Developers + +This track starts from familiar Python ideas, but these links are the canonical Rust instruction and runnable examples. A mapping is a learning aid, not a claim that the languages have the same runtime or semantics. + +| Python starting point | Rust concept to learn | Important difference | Canonical lesson | +|---|---|---|---| +| Reference counting and garbage collection | Ownership, moves, and borrowing | Rust does not trace object reachability; each value has an owner and borrowing has explicit rules. | [Ownership](../../01-core-fundamentals/ownership/README.md) | +| Mutable objects and aliases | Shared and exclusive references | Python permits aliases that can mutate an object; Rust permits either shared reads or one mutable borrow for a scope. | [Ownership](../../01-core-fundamentals/ownership/README.md) | +| `None` | `Option` | `None` is a singleton value; `Option` makes absence part of the type a caller must handle. | [Result and recoverable errors](../../02-standard-library/error_handling_basics/README.md) | +| Exceptions | `Result` and `?` | Python exceptions unwind control flow; ordinary Rust failure is returned in the type and propagated explicitly. | [Result and recoverable errors](../../02-standard-library/error_handling_basics/README.md) | +| Duck typing and protocols | Traits and generics | A Rust trait is declared and implemented explicitly; a generic bound is checked before the program runs. | [Traits and polymorphism](../../06-intermediate-rust/traits_and_polymorphism/README.md) | +| List comprehensions and generators | Iterator adapters | Rust iterators can borrow or consume their input, so the chosen iterator method affects later ownership. | [Iterator patterns](../../02-standard-library/iterator_patterns/README.md) | +| Lists and dictionaries | `Vec` and `HashMap` | Rust collections have uniform element types and expose ownership at their APIs. | [Collections](../../02-standard-library/collections/README.md) | +| `with` blocks and finalizers | Scope-based cleanup and `Drop` | Rust cleanup is tied to scope, not a garbage-collection or finalizer schedule. | [Ownership](../../01-core-fundamentals/ownership/README.md) | +| `asyncio` tasks | Futures, runtimes, and async boundaries | Creating a Rust future does not start it; it must be awaited or driven by an executor. | [Advanced async overview](../../07-advanced-concepts/advanced_async/README.md) | +| Virtual environments and `pip` | Cargo packages and dependency resolution | Cargo has different manifest, lockfile, and build conventions; do not treat it as a Python package installer. | [Tooling and quality](../../03-tooling-and-quality/README.md) | + +Start with ownership even when the immediate goal is faster code. It is the change that explains why the rest of the Rust API surface looks different. diff --git a/11-language-specific-tracks/PYTHON_TRACK/MVP_CHECKS.md b/11-language-specific-tracks/PYTHON_TRACK/MVP_CHECKS.md new file mode 100644 index 0000000..7880746 --- /dev/null +++ b/11-language-specific-tracks/PYTHON_TRACK/MVP_CHECKS.md @@ -0,0 +1,14 @@ +# Python-to-Rust Migration Checks + +Use these prompts after the comparison material. They test whether the mental-model change is clear; the linked canonical lessons provide the runnable instruction. + +| Focus | Python mental model | Rust mental model | Common mistake to avoid | Challenge | +|---|---|---|---|---| +| Values and aliases | Several names can refer to one mutable object. | A non-`Copy` value has one owner; aliases are explicit borrows with rules. | Adding `clone()` to silence every ownership error. | Explain what happens when a `String` is assigned to a second binding and name two ways to retain access to the original data. | +| Absence | A function may return `None` and callers may forget to check it. | A potentially missing value uses `Option`, which is handled with `match` or combinators. | Calling `unwrap()` for ordinary missing input. | Design a lookup signature for a possibly absent user and show how its caller handles both cases. | +| Errors | Exceptions can emerge from any call in the chain. | Recoverable errors appear as `Result` in the signature. | Replacing `try`/`except` with `unwrap()`. | Convert a parsing function that raises `ValueError` into a Rust signature and explain what `?` does. | +| Iteration | A comprehension creates a collection and a generator is lazily consumed. | Iterator adapters are lazy until consumed, and may borrow or take ownership. | Choosing `into_iter()` when the collection is needed afterwards. | Build the iterator chain for the even doubled values in a `Vec` and state whether it consumes the vector. | +| Dynamic behavior | Any object with the right method may be accepted at runtime. | A trait bound states the required capability and is checked at compile time. | Reaching for `Box` before a generic bound or enum is appropriate. | Specify a trait bound for a formatter function and explain when dynamic dispatch would be justified. | +| Async work | Scheduling a coroutine or task starts work under the event loop. | A future is inert until awaited or scheduled by a runtime. | Blocking an async runtime thread with a slow synchronous call. | Explain why creating a future is not enough to run it and where blocking file work belongs. | + +When an answer sounds like a syntax replacement, revisit the ownership or execution-model difference. That is normally where the Python-to-Rust translation changes shape. diff --git a/11-language-specific-tracks/PYTHON_TRACK/README.md b/11-language-specific-tracks/PYTHON_TRACK/README.md index d289377..e31246b 100644 --- a/11-language-specific-tracks/PYTHON_TRACK/README.md +++ b/11-language-specific-tracks/PYTHON_TRACK/README.md @@ -69,6 +69,8 @@ This track is designed for Python developers who want to learn Rust without losi - **CHEAT_SHEET.md** - Quick Python → Rust reference - **GOTCHAS.md** - Things that will surprise you - **TIPS_AND_TRICKS.md** - Productivity tips + - **CANONICAL_RUST_LINKS.md** - Canonical runnable Rust lessons for each comparison + - **MVP_CHECKS.md** - Short migration challenges that test the mental-model shift ## Realistic expectations diff --git a/11-language-specific-tracks/README.md b/11-language-specific-tracks/README.md index da5b904..cfa54df 100644 --- a/11-language-specific-tracks/README.md +++ b/11-language-specific-tracks/README.md @@ -4,6 +4,8 @@ Module 11 helps developers transitioning from other languages learn Rust idiomatically. Each track maps concepts from familiar languages to Rust equivalents. +Start with the [cross-language transition index](CROSS_LANGUAGE_COMPARISON.md) to select a track and find the canonical Rust lessons behind each comparison. + ## Available Tracks ### 1. Java Developer → Rust @@ -235,4 +237,3 @@ Each track includes: - Comparison articles and blog posts - Example repositories - Community forums - diff --git a/CONTENT_STATUS.md b/CONTENT_STATUS.md new file mode 100644 index 0000000..37e134d --- /dev/null +++ b/CONTENT_STATUS.md @@ -0,0 +1,56 @@ +# Content status + +This page gives learners and contributors a quick view of what is usable now and what still needs work. A status describes the evidence available for an area; it is not a score for the value or difficulty of the material. + +## Status definitions + +### Planned + +The intended topic or project is visible, but its learning material or runnable implementation has not been written. Empty directories, zero-byte files, and README-only project outlines belong here. + +A Planned item moves to Draft when it contains substantive material that can be reviewed, even if that material is incomplete. + +### Draft + +Substantive documentation or code exists, but there are known gaps, build failures, missing validation, or unresolved structural questions. Draft content can still be useful, but its limitations should be read before relying on it. + +A Draft item moves to Review when its known blocking issues are addressed and all applicable repository checks pass. + +### Review + +The material is usable and its applicable checks currently pass. Review does not mean that every optional exercise exists or that test coverage is complete. It means there is enough evidence to review the content against the formal learning rubric when that rubric is available. + +A Review item moves to Stable only after it passes both the applicable content rubric and automated validation. It returns to Draft if a correctness problem or validation failure is found. + +### Stable + +The material has passed the content rubric and automated validation. Those two requirements are still being developed, so no topic is Stable today. + +### Deprecated + +The material has been superseded and is no longer recommended as part of the learning path. A replacement and a clear migration note must exist before this status is used. No area is currently Deprecated. + +## Current overview + +| Area | Status | Evidence and remaining work | +|---|---|---| +| `00-setup-and-basics` | Review | Four Cargo packages are checked directly in CI. The module still needs more exercises and the formal content review. | +| `01-core-fundamentals` | Review | Ownership, borrowing, and lifetimes have direct Cargo jobs; the module's standalone topics are covered by `make check`. Overlapping early scaffolds still need normalization. | +| `02-standard-library` | Review | The module's examples are covered by `make check`. Duplicate or scaffold topic names remain to be reconciled. | +| `03-tooling-and-quality` | Review | The module's examples are covered by `make check`. Several older scaffold directories still need a canonical mapping. | +| `04-simple-programs` | Review | CI runs the workspace and standalone-example checks. Todo and rfind need stronger behavioral tests, and some physical project directories remain empty. | +| `05-cli-and-console-games` | Review | CI covers the Cargo workspace, the separate randomness package, and standalone examples. Game test depth varies, while Minesweeper, Snake, and the ASCII roguelike remain planned. | +| `06-intermediate-rust` | Review | This is the canonical Module 06 and is covered by `make check`. Its supplementary review material remains Draft and outside that check until it has validation coverage. The module still awaits the formal content rubric. | +| `07-advanced-concepts` | Draft | CI now covers the repaired SQLx, Axum, procedural-macro, benchmarking, SIMD, WebAssembly, and STM32 blinky examples. Database and hardware requirements are documented, but other advanced project groups and the broader learning material still need review. | +| `08-design-patterns` | Review | CI runs formatting, lint, workspace tests, standalone compilation, and design-document checks for all 23 patterns. Behavioral test coverage remains thin. | +| `09-mini-projects` | Mixed | Chat, HTTP server, key-value store, and load balancer are Review and covered as one CI workspace. Calculator, todo, note taker, and weather CLI are Planned documentation-only projects. | +| `10-real-world-rust` | Planned | Topic notes and a Makefile exist, but the five planned topic implementations do not. | +| `11-language-specific-tracks` | Mixed | The Java, Python, Go, and C++ overviews are Review. The four existing Java/Python Cargo projects are Draft because they are not in CI; Go and C++ projects remain planned. | +| `challenges` | Draft | Twenty-three Markdown files contain kata, beginner, interview, and level-guide material. There is no automated validation, and duplicate directory naming must be resolved without losing unique questions. | +| `resources` | Planned | The five tracked resource pages exist but are empty. They need a small, maintained set of recommendations. | + +## Changing a status + +A status change should be made in the same pull request as the evidence that supports it. Include the relevant build or validation command, describe any remaining gaps, and update this table if the status of a major area changes. + +Passing CI is necessary where checks apply, but it is not enough for Stable. Stable always requires both the content rubric and automated validation. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9400f4f..5626df3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -70,6 +70,12 @@ Run Cargo commands from the directory containing the relevant `Cargo.toml`. The repository intentionally has no root Cargo workspace. Do not commit generated `build/`, `target/`, or rustdoc files. +CI checks local links in every Markdown file with lychee in offline mode. If lychee is installed locally, run `lychee --offline --root-dir . --no-progress './**/*.md'` from the repository root before submitting documentation changes. + +Topics that contain `metadata.json` must follow the [content metadata contract](docs/content-metadata.md). Run `cargo run --manifest-path tools/contentctl/Cargo.toml -- validate ` against a metadata file or directory before submitting it. + +Use the [topic authoring guide](docs/authoring/topic-guide.md) when adding or substantially revising learning material. It covers topic boundaries, status evidence, validation, and the repository-to-website publishing boundary. + Exercises containing `broken_code.rs` are allowed to fail before the learner repairs them and are excluded from normal build checks. @@ -93,3 +99,5 @@ Reviewers will primarily consider: Use the issue template for incorrect explanations, build failures, learning-flow problems, or content proposals. Security concerns should not be posted in a public issue; follow [SECURITY.md](SECURITY.md) instead. + +When proposing a content change, check the [content status page](CONTENT_STATUS.md) for the area's known gaps and the evidence required to change its status. diff --git a/README.md b/README.md index fc92fcb..60122f9 100644 --- a/README.md +++ b/README.md @@ -4,43 +4,41 @@ # Rust Learning Lab -Rust Learning Lab is a collection of short explanations, runnable examples, -exercises, and small projects for learning Rust by writing code. It starts with -the language basics, spends time on ownership and borrowing, and then moves into -tooling, application design, concurrency, patterns, and project work. +Rust Learning Lab is a practical path through Rust: read a focused explanation, run a small program, change it, and use the compiler's feedback to deepen the idea. It supports both first-time Rust learners and experienced developers moving from Java, Python, Go, or C++. -The repository is intended for people learning Rust for the first time and for -developers coming from Java, Python, Go, C++, or a similar language. Examples -favour clarity over compactness so that the reason behind each Rust feature is -visible in the code. +The repository is actively growing. Most foundations, applications, intermediate material, and design-pattern examples are ready for review; some advanced projects and production topics are still Draft or Planned. [Content status](CONTENT_STATUS.md) explains the evidence behind each area, and the [roadmap](ROADMAP.md) records the remaining work. -## What is included +## Choose your starting point -- Focused examples that can be compiled and changed independently -- Exercises built around common mistakes and compiler feedback -- Concept notes, key takeaways, and suggested experiments -- Cargo projects for command-line applications and larger examples -- Make targets for compiling standalone examples and generating rustdoc output -- Transition guides for developers arriving from other languages +### New to Rust -The material is under active development. The foundations and intermediate -modules are usable now; some advanced project folders are still planned or are -being expanded. The [roadmap](ROADMAP.md) records that distinction. +Start with [`00-setup-and-basics`](00-setup-and-basics/), then work through [`01-core-fundamentals`](01-core-fundamentals/), [`02-standard-library`](02-standard-library/), and [`03-tooling-and-quality`](03-tooling-and-quality/). This route establishes the language, ownership model, standard library, testing, and everyday development tools. -## Prerequisites +### Ready to build programs -Install the stable Rust toolchain with `rustup`. You will need `rustc`, `cargo`, -`rustfmt`, `clippy`, Git, and Make. The included [toolchain file](rust-toolchain.toml) -selects the required Rust channel and components. +Move through [`04-simple-programs`](04-simple-programs/) and [`05-cli-and-console-games`](05-cli-and-console-games/) to combine I/O, algorithms, state, and user interaction. Continue to [`06-intermediate-rust`](06-intermediate-rust/) for ownership and borrowing, traits, generics, enums, and lifetimes. -Verify the installation: +### Moving from another language -```bash -rustc --version -cargo --version -``` +Use [`11-language-specific-tracks`](11-language-specific-tracks/) alongside the core path. The Java, Python, Go, and C++ guides connect familiar language features to Rust's ownership, error-handling, and type-system model without duplicating the core lessons. + +## Learning journeys + +| Journey | Modules | What you will practice | +|---|---|---| +| Foundations | [00](00-setup-and-basics/)–[03](03-tooling-and-quality/) | Syntax, ownership, standard types, testing, documentation, and tooling | +| Applied Rust | [04](04-simple-programs/)–[05](05-cli-and-console-games/) | Command-line programs, file handling, algorithms, state, and games | +| Type-system depth | [06](06-intermediate-rust/) | Traits, generics, enums, pattern matching, lifetimes, and optional supplementary review | +| Advanced reference | [07](07-advanced-concepts/)–[08](08-design-patterns/) | Networking, APIs, WebAssembly, macros, performance, and design patterns | +| Projects and production | [09](09-mini-projects/)–[10](10-real-world-rust/) | Multi-file programs, organization, deployment, profiling, and systems topics | + +The [learning path](LEARNING_PATH.md) gives the same sequence in a compact format. Module 06 also includes [supplementary review material](06-intermediate-rust/supplementary/README.md); it is useful after the primary sequence and remains Draft until it receives its own validation coverage. + +For the detailed beginner route, including stage checkpoints, use [From Zero: the canonical Rust path](docs/curriculum/from-zero.md). + +## Get running -## Getting started +Install the stable Rust toolchain with `rustup`, including `rustfmt` and `clippy`, plus Git and Make. The included [toolchain file](rust-toolchain.toml) selects the repository's Rust channel and components. ```bash git clone https://github.com/SaumilP/rust-learning-lab.git @@ -49,32 +47,7 @@ cd 00-setup-and-basics/hello_world cargo run ``` -If you already know the basics, use the [learning path](LEARNING_PATH.md) to -choose a suitable starting point. - -## Repository map - -| Module | Subject | Current role | -|---|---|---| -| [`00-setup-and-basics`](00-setup-and-basics/) | Installation, variables, data types, and control flow | Starting point | -| [`01-core-fundamentals`](01-core-fundamentals/) | Ownership, borrowing, lifetimes, functions, and errors | Core foundation | -| [`02-standard-library`](02-standard-library/) | Collections, strings, iterators, traits, and smart pointers | Core library skills | -| [`03-tooling-and-quality`](03-tooling-and-quality/) | Cargo, testing, documentation, debugging, and code quality | Development workflow | -| [`04-simple-programs`](04-simple-programs/) | Small command-line programs and file processing | Applied practice | -| [`05-cli-and-console-games`](05-cli-and-console-games/) | Console I/O, game loops, state, and randomness | Applied practice | -| [`06-intermediate-rust`](06-intermediate-rust/) | Modules, concurrency, async, macros, and deeper type-system work | Intermediate study | -| [`06-advanced-functions`](06-advanced-functions/) | Supplementary examples for generics, traits, enums, and ownership | Optional review | -| [`07-advanced-concepts`](07-advanced-concepts/) | Networking, web APIs, WebAssembly, procedural macros, and performance | Advanced reference | -| [`08-design-patterns`](08-design-patterns/) | Creational, structural, behavioural, and Rust-specific patterns | Pattern study | -| [`09-mini-projects`](09-mini-projects/) | Multi-file programs that combine several concepts | Project practice | -| [`10-real-world-rust`](10-real-world-rust/) | Profiling, unsafe Rust, FFI, deployment, and organization | Production topics | -| [`11-language-specific-tracks`](11-language-specific-tracks/) | Rust guidance for Java, Python, Go, and C++ developers | Transition guides | -| [`challenges`](challenges/) | Progressive practice and interview-style problems | Additional exercises | - -## Working with examples - -Many concept modules contain standalone `.rs` files instead of Cargo packages. -Run their Makefile from the module directory: +Many concept modules use standalone Rust files. Run their Makefile from the module directory: ```bash cd 01-core-fundamentals @@ -84,12 +57,9 @@ make check make clean ``` -`make check` verifies formatting, compiles the examples with warnings denied, -runs embedded tests, and generates rustdoc pages under `build/docs/`. Generated -files are temporary; `make clean` removes the complete `build/` directory. +`make check` formats, compiles, tests, and documents the module's checked examples. Generated `build/` and `target/` directories are disposable. Some exercises intentionally begin with broken code; read the problem statement before treating those compiler errors as repository defects. -For a Cargo workspace or package, use Cargo from the directory containing its -`Cargo.toml`: +For a Cargo package or workspace, run Cargo from the directory containing its `Cargo.toml`: ```bash cd 04-simple-programs @@ -97,36 +67,17 @@ cargo run -p calculator cargo test --workspace ``` -Some exercises are deliberately incomplete and should not compile until you -repair them. Read the exercise instructions before treating a compiler error as -a repository defect. - -## A practical study routine - -1. Read the topic's `README.md` and `key_takeaways.md`. -2. Run the example without changing it. -3. Predict the result of a small change, then test that prediction. -4. Complete the related exercise using the compiler messages as feedback. -5. Apply the topic in a program from modules 04, 05, or 09. - -## Project status and quality - -Continuous integration checks the tracked Cargo packages and the standalone -examples used by the main learning modules. Local checks should be run before a -pull request; the exact commands are documented in -[CONTRIBUTING.md](CONTRIBUTING.md). +## Study routine -Planned additions and known content gaps are listed in [ROADMAP.md](ROADMAP.md). -For a compact sequence through the current material, see -[LEARNING_PATH.md](LEARNING_PATH.md). +1. Read the topic `README.md` and `key_takeaways.md`. +2. Run the example before changing it. +3. Predict a small change, then test that prediction. +4. Repair the related exercise using compiler feedback. +5. Apply the idea in a program or project before moving on. -## Contributing +## Contribute -Corrections, clearer explanations, new exercises, tests, and small focused -examples are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) before -opening a pull request. Community expectations are described in the -[Code of Conduct](CODE_OF_CONDUCT.md), and security reports should follow -[SECURITY.md](SECURITY.md). +Corrections, clearer explanations, focused examples, exercises, and tests are welcome. Read [CONTRIBUTING.md](CONTRIBUTING.md) for the learning-content standards and validation commands, [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for community expectations, and [SECURITY.md](SECURITY.md) for security reporting. ## License diff --git a/ROADMAP.md b/ROADMAP.md index 6812f8d..73bb778 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,8 +1,6 @@ # Rust Learning Lab Roadmap -This roadmap separates material that is ready to study from work that still -needs attention. It is a repository status document, not a promise that every -directory is complete. +This roadmap describes what work remains. The [content status page](CONTENT_STATUS.md) records the current state of each major area and the evidence behind it. ## Current learning path @@ -71,8 +69,6 @@ which version is authoritative: improves understanding. - Add measurement-driven examples for benchmarking and profiling. - Add explicit safety contracts to every unsafe Rust and FFI example. -- Clarify the relationship between `06-advanced-functions` and - `06-intermediate-rust`. ### Curate resources and maintenance guidance @@ -83,7 +79,7 @@ which version is authoritative: ## Completion criteria for a topic -A topic is considered ready when it has: +A topic is considered ready for Review when it has: - A short explanation of what the concept solves and when to use it - At least one focused example that builds on stable Rust diff --git a/assets/social-preview.png b/assets/social-preview.png new file mode 100644 index 0000000..7b3b271 Binary files /dev/null and b/assets/social-preview.png differ diff --git a/challenges/README.md b/challenges/README.md index 049e15c..9272e2f 100644 Binary files a/challenges/README.md and b/challenges/README.md differ diff --git a/challenges/code-review/README.md b/challenges/code-review/README.md new file mode 100644 index 0000000..f3a2931 --- /dev/null +++ b/challenges/code-review/README.md @@ -0,0 +1,5 @@ +# Code review challenges + +These short reviews ask you to identify the most important issue in working or nearly working Rust, explain its learner-visible consequence, and suggest a proportionate improvement. They are not style quizzes: a good answer connects the code to correctness, ownership, error handling, or API design. + +The items in [items/](./items/) use the validated quiz format with `type: "code_review"`. Make a review note before reading the stored answer, then use the canonical lesson reference to study the underlying rule. diff --git a/challenges/code-review/items/01-unnecessary-clone.json b/challenges/code-review/items/01-unnecessary-clone.json new file mode 100644 index 0000000..d189f62 --- /dev/null +++ b/challenges/code-review/items/01-unnecessary-clone.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"code-review-unnecessary-clone","type":"code_review","topic":"ownership","difficulty":"beginner","concepts":["ownership","clone","api-design"],"question":"Review this function. What is the unnecessary operation, and what parameter type better communicates its read-only purpose?","code":"fn print_title(title: String) {\n let copy = title.clone();\n println!(\"{copy}\");\n}","choices":[],"answer":{"kind":"review","value":"The clone is unnecessary because the function only reads the text. Accept `&str` and print it directly, so callers retain ownership without an allocation."},"explanation":"The function does not need an owned string or a duplicate allocation. A borrowed string slice describes the least permission it needs and accepts more caller types.","references":[{"title":"Ownership","path":"../../../01-core-fundamentals/ownership/README.md"}]} diff --git a/challenges/code-review/items/02-panic-on-input.json b/challenges/code-review/items/02-panic-on-input.json new file mode 100644 index 0000000..19b8298 --- /dev/null +++ b/challenges/code-review/items/02-panic-on-input.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"code-review-panic-on-input","type":"code_review","topic":"result","difficulty":"beginner","concepts":["result","error-handling","api-design"],"question":"Review this parser for user input. What behaviour should the API expose instead of panicking?","code":"fn parse_age(input: &str) -> u8 {\n input.parse().unwrap()\n}","choices":[],"answer":{"kind":"review","value":"Invalid input is an expected outcome, so return `Result` or a domain error instead of calling `unwrap`. The caller can then report or recover from the parse failure."},"explanation":"A panic removes the caller’s ability to decide how invalid user input is handled. `Result` preserves that decision at the API boundary.","references":[{"title":"Option and Result handling","path":"../../../02-standard-library/error_handling_basics/README.md"}]} diff --git a/challenges/code-review/items/03-indexed-utf8.json b/challenges/code-review/items/03-indexed-utf8.json new file mode 100644 index 0000000..e27575c --- /dev/null +++ b/challenges/code-review/items/03-indexed-utf8.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"code-review-indexed-utf8","type":"code_review","topic":"string-operations","difficulty":"intermediate","concepts":["strings","utf8","collections"],"question":"Review this attempt to return the first character. Why is the indexing approach unsuitable, and what iterator-based replacement handles UTF-8 safely?","code":"fn first_letter(text: &str) -> char {\n text[0]\n}","choices":[],"answer":{"kind":"review","value":"Rust strings cannot be indexed by integer because UTF-8 characters vary in byte length. Use `text.chars().next()` and return an `Option` to represent empty input."},"explanation":"A byte offset is not generally a character boundary. Iterating over `chars` respects Unicode scalar boundaries, while `Option` handles the empty-string case honestly.","references":[{"title":"String operations","path":"../../../02-standard-library/string_operations/README.md"}]} diff --git a/challenges/code-review/items/04-boolean-state.json b/challenges/code-review/items/04-boolean-state.json new file mode 100644 index 0000000..aec815a --- /dev/null +++ b/challenges/code-review/items/04-boolean-state.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"code-review-boolean-state","type":"code_review","topic":"enums-pattern-matching","difficulty":"beginner","concepts":["enums","state-modeling","invariants"],"question":"Review this state representation. What invalid states can it represent, and what Rust type would make the alternatives explicit?","code":"struct RequestState {\n pending: bool,\n succeeded: bool,\n failed: bool,\n}","choices":[],"answer":{"kind":"review","value":"The flags allow contradictory combinations such as pending and succeeded. Replace them with an enum such as `Pending`, `Succeeded`, and `Failed` (with payloads where needed)."},"explanation":"An enum makes mutually exclusive states structural rather than a convention every caller must remember.","references":[{"title":"Enums and pattern matching","path":"../../../06-intermediate-rust/enums_and_pattern_matching/README.md"}]} diff --git a/challenges/code-review/items/05-repeated-search.json b/challenges/code-review/items/05-repeated-search.json new file mode 100644 index 0000000..430ae22 --- /dev/null +++ b/challenges/code-review/items/05-repeated-search.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"code-review-repeated-search","type":"code_review","topic":"collections","difficulty":"intermediate","concepts":["collections","performance","hashmap"],"question":"Review this lookup loop. What grows unnecessarily as the input grows, and which collection better fits repeated lookups by identifier?","code":"fn has_all_ids(ids: &[u32], wanted: &[u32]) -> bool {\n wanted.iter().all(|id| ids.iter().any(|candidate| candidate == id))\n}","choices":[],"answer":{"kind":"review","value":"Each requested ID scans `ids`, producing repeated linear searches. Build a `HashSet` from `ids` when repeated membership checks justify the setup cost."},"explanation":"The current approach can be quadratic in the number of IDs and requests. A set makes the intended membership operation explicit and usually gives faster repeated lookups.","references":[{"title":"Collections","path":"../../../02-standard-library/collections/README.md"}]} diff --git a/challenges/code-review/items/06-public-concrete-type.json b/challenges/code-review/items/06-public-concrete-type.json new file mode 100644 index 0000000..bb26a11 --- /dev/null +++ b/challenges/code-review/items/06-public-concrete-type.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"code-review-public-concrete-type","type":"code_review","topic":"traits","difficulty":"intermediate","concepts":["traits","api-design","abstraction"],"question":"Review this public helper. How could its parameter be broadened without allocating or forcing callers to construct a `Vec`?","code":"pub fn print_all(names: &Vec) {\n for name in names {\n println!(\"{name}\");\n }\n}","choices":[],"answer":{"kind":"review","value":"Accept a slice, `&[String]`, when the function only needs to iterate over existing names. That works with vectors and slices without exposing a needless concrete collection requirement."},"explanation":"Public signatures should ask for the capabilities they need. A slice expresses read-only sequential access more generally than `&Vec`.","references":[{"title":"Traits and polymorphism","path":"../../../06-intermediate-rust/traits_and_polymorphism/README.md"}]} diff --git a/challenges/interview/README.md b/challenges/interview/README.md new file mode 100644 index 0000000..79ac3b8 --- /dev/null +++ b/challenges/interview/README.md @@ -0,0 +1,7 @@ +# Rust interview taxonomy + +The interview track is organized by competency, not as a random question list. Its 11 categories define the progression for future interview prompts, from language fundamentals through systems design and code review. + +Category data lives in [taxonomy/](./taxonomy/) as validated JSON. Each category records its learning focus, suitable audience levels, and canonical lessons. RLL-066 will add individual questions to this structure; this taxonomy does not pretend those questions already exist. + +Validate the category files with `cargo run --manifest-path tools/contentctl/Cargo.toml -- validate-interview challenges/interview/taxonomy`. diff --git a/challenges/interview/questions/01-language-fundamentals.json b/challenges/interview/questions/01-language-fundamentals.json new file mode 100644 index 0000000..67c753f --- /dev/null +++ b/challenges/interview/questions/01-language-fundamentals.json @@ -0,0 +1 @@ +{"schema_version":1,"category":"language-fundamentals","questions":[{"id":"interview-fundamentals-01","level":"foundation","focus":["bindings"],"prompt":"Explain the difference between `let` and `let mut`.","evaluation_criteria":["States immutability is default","Explains binding-level mutability"]},{"id":"interview-fundamentals-02","level":"foundation","focus":["shadowing"],"prompt":"When would you shadow a binding instead of making it mutable?","evaluation_criteria":["Explains new binding","Notes type changes are possible"]},{"id":"interview-fundamentals-03","level":"foundation","focus":["control-flow"],"prompt":"Why can an `if` expression initialize a variable?","evaluation_criteria":["Identifies expression value","Mentions compatible branch types"]},{"id":"interview-fundamentals-04","level":"foundation","focus":["functions"],"prompt":"What changes when a final function expression gains a semicolon?","evaluation_criteria":["Distinguishes expression and statement","Explains unit return"]},{"id":"interview-fundamentals-05","level":"foundation","focus":["match"],"prompt":"What safety property does exhaustive `match` provide?","evaluation_criteria":["Names all variants handled","Connects to future cases"]},{"id":"interview-fundamentals-06","level":"foundation","focus":["types"],"prompt":"When is a type annotation useful despite inference?","evaluation_criteria":["Names ambiguity or public API","Avoids claiming inference is unreliable"]},{"id":"interview-fundamentals-07","level":"working_rust_developer","focus":["loops"],"prompt":"Compare `loop`, `while`, and `for` for iteration over a collection.","evaluation_criteria":["Recommends for for iterators","Notes explicit conditions"]},{"id":"interview-fundamentals-08","level":"foundation","focus":["strings"],"prompt":"Why are `char` and `&str` distinct types?","evaluation_criteria":["Distinguishes scalar and slice","Mentions UTF-8 context"]},{"id":"interview-fundamentals-09","level":"working_rust_developer","focus":["modules"],"prompt":"How would you decide whether a helper should be public?","evaluation_criteria":["Considers API boundary","Prefers minimal visibility"]}]} diff --git a/challenges/interview/questions/02-ownership-and-lifetimes.json b/challenges/interview/questions/02-ownership-and-lifetimes.json new file mode 100644 index 0000000..cabb5e8 --- /dev/null +++ b/challenges/interview/questions/02-ownership-and-lifetimes.json @@ -0,0 +1,93 @@ +{ + "schema_version": 1, + "category": "ownership-and-lifetimes", + "questions": [ + { + "id": "interview-ownership-01", + "level": "foundation", + "focus": ["moves"], + "prompt": "What happens when one `String` binding is assigned to another?", + "evaluation_criteria": ["Explains ownership move", "Contrasts Copy types"] + }, + { + "id": "interview-ownership-02", + "level": "foundation", + "focus": ["borrowing"], + "prompt": "Why can many immutable references coexist?", + "evaluation_criteria": [ + "Identifies read-only access", + "Connects to race prevention" + ] + }, + { + "id": "interview-ownership-03", + "level": "foundation", + "focus": ["borrowing"], + "prompt": "Why is overlapping mutable access restricted?", + "evaluation_criteria": [ + "Names exclusive mutation", + "Explains aliasing risk" + ] + }, + { + "id": "interview-ownership-04", + "level": "working_rust_developer", + "focus": ["api-design"], + "prompt": "Choose between `String`, `&str`, and `&mut String` for a display-only API.", + "evaluation_criteria": [ + "Chooses least permission", + "Explains caller flexibility" + ] + }, + { + "id": "interview-ownership-05", + "level": "working_rust_developer", + "focus": ["lifetimes"], + "prompt": "What question do lifetime annotations answer?", + "evaluation_criteria": [ + "Relates references", + "Says annotations do not extend data life" + ] + }, + { + "id": "interview-ownership-06", + "level": "working_rust_developer", + "focus": ["slices"], + "prompt": "Why return `&str` for a substring when possible?", + "evaluation_criteria": [ + "Avoids allocation", + "Acknowledges source lifetime" + ] + }, + { + "id": "interview-ownership-07", + "level": "senior_rust_developer", + "focus": ["api-design"], + "prompt": "How would you review an API that clones every input?", + "evaluation_criteria": [ + "Checks ownership need", + "Balances simplicity and cost" + ] + }, + { + "id": "interview-ownership-08", + "level": "working_rust_developer", + "focus": ["non-lexical-lifetimes"], + "prompt": "What lets a mutation follow a completed immutable borrow?", + "evaluation_criteria": [ + "Names last use", + "Avoids claiming scopes alone decide" + ] + }, + { + "id": "interview-ownership-09", + "level": "senior_rust_developer", + "focus": ["self-references"], + "prompt": "Why are self-referential structures difficult in safe Rust?", + "evaluation_criteria": [ + "Mentions moves invalidate pointers", + "Discusses safer designs" + ] + } + ] +} diff --git a/challenges/interview/questions/03-type-system.json b/challenges/interview/questions/03-type-system.json new file mode 100644 index 0000000..e443183 --- /dev/null +++ b/challenges/interview/questions/03-type-system.json @@ -0,0 +1 @@ +{"schema_version":1,"category":"type-system","questions":[{"id":"interview-types-01","level":"foundation","focus":["enums"],"prompt":"When is an enum better than several optional fields?","evaluation_criteria":["Models exclusive states","Prevents invalid combinations"]},{"id":"interview-types-02","level":"foundation","focus":["traits"],"prompt":"What problem does a trait solve?","evaluation_criteria":["Describes shared behaviour","Avoids inheritance equivalence"]},{"id":"interview-types-03","level":"working_rust_developer","focus":["generics"],"prompt":"When would you choose a generic parameter?","evaluation_criteria":["Explains static dispatch","Names capability bounds"]},{"id":"interview-types-04","level":"working_rust_developer","focus":["trait-objects"],"prompt":"When is `dyn Trait` appropriate?","evaluation_criteria":["Explains runtime polymorphism","Names trade-offs"]},{"id":"interview-types-05","level":"foundation","focus":["option"],"prompt":"Why is `Option` preferable to a sentinel value?","evaluation_criteria":["Makes absence explicit","Requires handling"]},{"id":"interview-types-06","level":"working_rust_developer","focus":["result"],"prompt":"When should an API return `Result`?","evaluation_criteria":["Distinguishes recoverable failure","Preserves caller choice"]},{"id":"interview-types-07","level":"senior_rust_developer","focus":["newtypes"],"prompt":"What value can a newtype add around a primitive?","evaluation_criteria":["Adds domain meaning","Prevents invalid mixing"]},{"id":"interview-types-08","level":"working_rust_developer","focus":["derive"],"prompt":"When is deriving a trait preferable to manual implementation?","evaluation_criteria":["Recognizes standard semantics","Notes custom invariants"]},{"id":"interview-types-09","level":"senior_rust_developer","focus":["associated-types"],"prompt":"Why use an associated type instead of another generic parameter?","evaluation_criteria":["Explains one natural relationship","Discusses API clarity"]}]} diff --git a/challenges/interview/questions/04-concurrency.json b/challenges/interview/questions/04-concurrency.json new file mode 100644 index 0000000..3cf4f70 --- /dev/null +++ b/challenges/interview/questions/04-concurrency.json @@ -0,0 +1 @@ +{"schema_version":1,"category":"concurrency","questions":[{"id":"interview-concurrency-01","level":"working_rust_developer","focus":["send-sync"],"prompt":"What do `Send` and `Sync` express?","evaluation_criteria":["Defines thread transfer and sharing","Avoids treating them as locks"]},{"id":"interview-concurrency-02","level":"working_rust_developer","focus":["channels"],"prompt":"When would you prefer a channel to shared mutable state?","evaluation_criteria":["Explains ownership transfer","Names coordination trade-off"]},{"id":"interview-concurrency-03","level":"working_rust_developer","focus":["mutex"],"prompt":"What should a mutex guard protect?","evaluation_criteria":["Names invariant","Limits lock duration"]},{"id":"interview-concurrency-04","level":"senior_rust_developer","focus":["deadlocks"],"prompt":"How would you reduce deadlock risk?","evaluation_criteria":["Uses lock ordering or design change","Discusses scope"]},{"id":"interview-concurrency-05","level":"working_rust_developer","focus":["arc"],"prompt":"Why is `Arc` used across threads instead of `Rc`?","evaluation_criteria":["Names atomic counting","Notes overhead"]},{"id":"interview-concurrency-06","level":"senior_rust_developer","focus":["data-races"],"prompt":"How does Rust prevent data races in safe code?","evaluation_criteria":["Connects aliases and mutation","Mentions type bounds"]},{"id":"interview-concurrency-07","level":"senior_rust_developer","focus":["contention"],"prompt":"How would you investigate lock contention?","evaluation_criteria":["Measures before changing","Considers ownership redesign"]},{"id":"interview-concurrency-08","level":"working_rust_developer","focus":["threads"],"prompt":"What makes a thread boundary an API boundary?","evaluation_criteria":["Considers owned inputs","Considers failure handling"]},{"id":"interview-concurrency-09","level":"senior_rust_developer","focus":["parallelism"],"prompt":"When can parallel work make a program slower?","evaluation_criteria":["Names overhead or contention","Considers workload size"]}]} diff --git a/challenges/interview/questions/05-async.json b/challenges/interview/questions/05-async.json new file mode 100644 index 0000000..7d7cf02 --- /dev/null +++ b/challenges/interview/questions/05-async.json @@ -0,0 +1 @@ +{"schema_version":1,"category":"async","questions":[{"id":"interview-async-01","level":"working_rust_developer","focus":["futures"],"prompt":"What is a future before it is awaited?","evaluation_criteria":["Describes deferred work","Avoids claiming a thread starts"]},{"id":"interview-async-02","level":"working_rust_developer","focus":["await"],"prompt":"What does `.await` permit an executor to do?","evaluation_criteria":["Explains suspension","Notes task progress"]},{"id":"interview-async-03","level":"working_rust_developer","focus":["blocking"],"prompt":"Why avoid blocking calls in async tasks?","evaluation_criteria":["Explains executor starvation","Suggests boundary"]},{"id":"interview-async-04","level":"senior_rust_developer","focus":["cancellation"],"prompt":"What must a cancellation-safe operation preserve?","evaluation_criteria":["Names partial progress concern","Discusses cleanup"]},{"id":"interview-async-05","level":"working_rust_developer","focus":["send"],"prompt":"Why might a spawned future require `Send`?","evaluation_criteria":["Explains task movement","Notes executor policy"]},{"id":"interview-async-06","level":"working_rust_developer","focus":["lifetimes"],"prompt":"Why are borrowed values awkward in spawned tasks?","evaluation_criteria":["Explains task outlives scope","Suggests ownership"]},{"id":"interview-async-07","level":"senior_rust_developer","focus":["backpressure"],"prompt":"How would you limit async work under load?","evaluation_criteria":["Uses bounded concurrency","Discusses overload"]},{"id":"interview-async-08","level":"senior_rust_developer","focus":["timeouts"],"prompt":"What should a timeout policy decide?","evaluation_criteria":["Names cancellation or retry","Considers user impact"]},{"id":"interview-async-09","level":"working_rust_developer","focus":["testing"],"prompt":"How would you test async failure paths?","evaluation_criteria":["Controls dependencies","Asserts outcomes"]}]} diff --git a/challenges/interview/questions/06-api-design.json b/challenges/interview/questions/06-api-design.json new file mode 100644 index 0000000..519ddd8 --- /dev/null +++ b/challenges/interview/questions/06-api-design.json @@ -0,0 +1 @@ +{"schema_version":1,"category":"api-design","questions":[{"id":"interview-api-01","level":"working_rust_developer","focus":["errors"],"prompt":"How do you choose between `Option` and `Result`?","evaluation_criteria":["Separates absence and failure","Uses caller needs"]},{"id":"interview-api-02","level":"working_rust_developer","focus":["ownership"],"prompt":"How do signature choices signal ownership?","evaluation_criteria":["Compares owned and borrowed","Uses least permission"]},{"id":"interview-api-03","level":"working_rust_developer","focus":["visibility"],"prompt":"Why keep public APIs small?","evaluation_criteria":["Names compatibility cost","Encourages encapsulation"]},{"id":"interview-api-04","level":"senior_rust_developer","focus":["errors"],"prompt":"What makes an error type useful to callers?","evaluation_criteria":["Provides context","Avoids leaking internals"]},{"id":"interview-api-05","level":"working_rust_developer","focus":["collections"],"prompt":"Why accept a slice instead of `&Vec`?","evaluation_criteria":["Names broader input","Limits required capability"]},{"id":"interview-api-06","level":"senior_rust_developer","focus":["versioning"],"prompt":"How would you evolve a public enum?","evaluation_criteria":["Considers downstream matches","Discusses compatibility"]},{"id":"interview-api-07","level":"working_rust_developer","focus":["builders"],"prompt":"When is a builder preferable to many parameters?","evaluation_criteria":["Names optional configuration","Maintains invariants"]},{"id":"interview-api-08","level":"senior_rust_developer","focus":["traits"],"prompt":"When should a public trait be sealed or narrow?","evaluation_criteria":["Considers external implementations","Explains evolution"]},{"id":"interview-api-09","level":"senior_rust_developer","focus":["invariants"],"prompt":"Where should an API enforce invariants?","evaluation_criteria":["Prefers construction boundary","Avoids delayed failure"]}]} diff --git a/challenges/interview/questions/07-performance.json b/challenges/interview/questions/07-performance.json new file mode 100644 index 0000000..85e1b5f --- /dev/null +++ b/challenges/interview/questions/07-performance.json @@ -0,0 +1 @@ +{"schema_version":1,"category":"performance","questions":[{"id":"interview-performance-01","level":"senior_rust_developer","focus":["measurement"],"prompt":"What should you measure before optimizing?","evaluation_criteria":["Names workload","Uses profiling"]},{"id":"interview-performance-02","level":"senior_rust_developer","focus":["allocation"],"prompt":"How would you find allocation pressure?","evaluation_criteria":["Measures allocations","Considers ownership"]},{"id":"interview-performance-03","level":"senior_rust_developer","focus":["algorithms"],"prompt":"When does Big O miss performance reality?","evaluation_criteria":["Names constants or cache","Uses measurements"]},{"id":"interview-performance-04","level":"systems_performance_specialist","focus":["layout"],"prompt":"How can data layout affect speed?","evaluation_criteria":["Mentions locality","Considers representation"]},{"id":"interview-performance-05","level":"senior_rust_developer","focus":["cloning"],"prompt":"How would you review frequent cloning?","evaluation_criteria":["Checks necessity","Balances complexity"]},{"id":"interview-performance-06","level":"systems_performance_specialist","focus":["benchmarks"],"prompt":"What makes a benchmark misleading?","evaluation_criteria":["Names unrealistic input","Controls variance"]},{"id":"interview-performance-07","level":"senior_rust_developer","focus":["iterators"],"prompt":"When are iterator chains a good choice?","evaluation_criteria":["Explains clarity","Avoids blanket speed claim"]},{"id":"interview-performance-08","level":"systems_performance_specialist","focus":["parallelism"],"prompt":"How do you choose parallelism granularity?","evaluation_criteria":["Considers overhead","Measures workload"]},{"id":"interview-performance-09","level":"senior_rust_developer","focus":["regressions"],"prompt":"How would you prevent a performance regression?","evaluation_criteria":["Adds representative benchmark","Defines threshold"]}]} diff --git a/challenges/interview/questions/08-unsafe-and-ffi.json b/challenges/interview/questions/08-unsafe-and-ffi.json new file mode 100644 index 0000000..980d5dc --- /dev/null +++ b/challenges/interview/questions/08-unsafe-and-ffi.json @@ -0,0 +1 @@ +{"schema_version":1,"category":"unsafe-and-ffi","questions":[{"id":"interview-unsafe-01","level":"senior_rust_developer","focus":["unsafe"],"prompt":"What belongs in an unsafe safety comment?","evaluation_criteria":["States invariants","Names caller obligations"]},{"id":"interview-unsafe-02","level":"senior_rust_developer","focus":["pointers"],"prompt":"What must be true before dereferencing a raw pointer?","evaluation_criteria":["Names validity and alignment","Considers aliasing"]},{"id":"interview-unsafe-03","level":"systems_performance_specialist","focus":["ffi"],"prompt":"What should an FFI boundary validate?","evaluation_criteria":["Checks pointers and lengths","Defines ownership"]},{"id":"interview-unsafe-04","level":"senior_rust_developer","focus":["encapsulation"],"prompt":"Why isolate unsafe code?","evaluation_criteria":["Limits audit surface","Provides safe API"]},{"id":"interview-unsafe-05","level":"systems_performance_specialist","focus":["repr"],"prompt":"When does `repr(C)` matter?","evaluation_criteria":["Names ABI boundary","Avoids layout assumptions"]},{"id":"interview-unsafe-06","level":"senior_rust_developer","focus":["soundness"],"prompt":"How would you test an unsafe abstraction?","evaluation_criteria":["Tests invariants","Uses adversarial cases"]},{"id":"interview-unsafe-07","level":"systems_performance_specialist","focus":["uninitialized"],"prompt":"What makes uninitialized memory dangerous?","evaluation_criteria":["Names invalid reads","Uses initialization contract"]},{"id":"interview-unsafe-08","level":"senior_rust_developer","focus":["foreign-errors"],"prompt":"How should an FFI API report failure?","evaluation_criteria":["Avoids unwinding boundary","Defines status contract"]},{"id":"interview-unsafe-09","level":"systems_performance_specialist","focus":["audit"],"prompt":"What would you inspect first in an unsafe review?","evaluation_criteria":["Finds invariants","Traces all callers"]}]} diff --git a/challenges/interview/questions/09-testing-and-tooling.json b/challenges/interview/questions/09-testing-and-tooling.json new file mode 100644 index 0000000..72f3d1d --- /dev/null +++ b/challenges/interview/questions/09-testing-and-tooling.json @@ -0,0 +1 @@ +{"schema_version":1,"category":"testing-and-tooling","questions":[{"id":"interview-tooling-01","level":"foundation","focus":["tests"],"prompt":"What should a unit test prove?","evaluation_criteria":["Names behaviour","Avoids implementation detail"]},{"id":"interview-tooling-02","level":"working_rust_developer","focus":["integration-tests"],"prompt":"When use an integration test?","evaluation_criteria":["Names public interface","Contrasts unit tests"]},{"id":"interview-tooling-03","level":"working_rust_developer","focus":["clippy"],"prompt":"How do you handle a Clippy finding?","evaluation_criteria":["Evaluates warning","Avoids blind suppression"]},{"id":"interview-tooling-04","level":"working_rust_developer","focus":["debugging"],"prompt":"What is your first debugging step?","evaluation_criteria":["Reproduces issue","Collects evidence"]},{"id":"interview-tooling-05","level":"senior_rust_developer","focus":["property-testing"],"prompt":"When is property testing useful?","evaluation_criteria":["Names invariants","Generates broad inputs"]},{"id":"interview-tooling-06","level":"foundation","focus":["cargo"],"prompt":"What is the role of Cargo.lock?","evaluation_criteria":["Names resolution record","Distinguishes manifest"]},{"id":"interview-tooling-07","level":"working_rust_developer","focus":["ci"],"prompt":"What belongs in a reliable CI check?","evaluation_criteria":["Names deterministic validation","Avoids hidden setup"]},{"id":"interview-tooling-08","level":"senior_rust_developer","focus":["flaky-tests"],"prompt":"How would you investigate a flaky test?","evaluation_criteria":["Captures conditions","Avoids retries as fix"]},{"id":"interview-tooling-09","level":"working_rust_developer","focus":["documentation"],"prompt":"What makes API documentation useful?","evaluation_criteria":["Explains intent","Shows constraints"]}]} diff --git a/challenges/interview/questions/10-system-design.json b/challenges/interview/questions/10-system-design.json new file mode 100644 index 0000000..9e8a504 --- /dev/null +++ b/challenges/interview/questions/10-system-design.json @@ -0,0 +1 @@ +{"schema_version":1,"category":"system-design","questions":[{"id":"interview-design-01","level":"senior_rust_developer","focus":["requirements"],"prompt":"What do you clarify before designing a service?","evaluation_criteria":["Names load and goals","States assumptions"]},{"id":"interview-design-02","level":"senior_rust_developer","focus":["boundaries"],"prompt":"How do you choose service boundaries?","evaluation_criteria":["Uses ownership of data","Considers failure modes"]},{"id":"interview-design-03","level":"senior_rust_developer","focus":["reliability"],"prompt":"What makes a retry safe?","evaluation_criteria":["Names idempotency","Uses backoff"]},{"id":"interview-design-04","level":"senior_rust_developer","focus":["observability"],"prompt":"What signals would you expose first?","evaluation_criteria":["Names metrics and logs","Connects to goals"]},{"id":"interview-design-05","level":"systems_performance_specialist","focus":["capacity"],"prompt":"How would you plan capacity?","evaluation_criteria":["Uses workload model","Allows headroom"]},{"id":"interview-design-06","level":"senior_rust_developer","focus":["storage"],"prompt":"How do consistency needs affect storage?","evaluation_criteria":["Names invariants","Explains trade-off"]},{"id":"interview-design-07","level":"senior_rust_developer","focus":["security"],"prompt":"What boundary should validate untrusted input?","evaluation_criteria":["Validates early","Preserves context"]},{"id":"interview-design-08","level":"senior_rust_developer","focus":["rollout"],"prompt":"How would you deploy a risky change?","evaluation_criteria":["Uses staged rollout","Defines rollback"]},{"id":"interview-design-09","level":"systems_performance_specialist","focus":["failure"],"prompt":"How should a service degrade?","evaluation_criteria":["Prioritizes core work","Communicates limits"]}]} diff --git a/challenges/interview/questions/11-code-review.json b/challenges/interview/questions/11-code-review.json new file mode 100644 index 0000000..5369b4c --- /dev/null +++ b/challenges/interview/questions/11-code-review.json @@ -0,0 +1 @@ +{"schema_version":1,"category":"code-review","questions":[{"id":"interview-review-01","level":"working_rust_developer","focus":["correctness"],"prompt":"How do you prioritize review findings?","evaluation_criteria":["Starts with correctness","Explains impact"]},{"id":"interview-review-02","level":"working_rust_developer","focus":["ownership"],"prompt":"What ownership issues do you inspect first?","evaluation_criteria":["Checks needless clones","Checks API transfers"]},{"id":"interview-review-03","level":"senior_rust_developer","focus":["errors"],"prompt":"How do you review error handling?","evaluation_criteria":["Finds panics at boundaries","Checks useful context"]},{"id":"interview-review-04","level":"working_rust_developer","focus":["readability"],"prompt":"When is a review comment about readability useful?","evaluation_criteria":["Connects to maintenance","Offers concrete change"]},{"id":"interview-review-05","level":"senior_rust_developer","focus":["performance"],"prompt":"How do you raise a performance concern?","evaluation_criteria":["Avoids speculation","Requests evidence"]},{"id":"interview-review-06","level":"senior_rust_developer","focus":["concurrency"],"prompt":"What concurrency hazards merit review attention?","evaluation_criteria":["Names shared-state invariant","Considers blocking"]},{"id":"interview-review-07","level":"working_rust_developer","focus":["tests"],"prompt":"What makes a missing test worth mentioning?","evaluation_criteria":["Names behaviour gap","Suggests boundary case"]},{"id":"interview-review-08","level":"senior_rust_developer","focus":["api-design"],"prompt":"How do you review a public signature?","evaluation_criteria":["Checks capability fit","Considers compatibility"]},{"id":"interview-review-09","level":"systems_performance_specialist","focus":["unsafe"],"prompt":"How do you review an unsafe block?","evaluation_criteria":["Finds safety contract","Traces invariant"]},{"id":"interview-review-10","level":"senior_rust_developer","focus":["communication"],"prompt":"How should a review handle a nonblocking suggestion?","evaluation_criteria":["Labels priority","Keeps tone actionable"]}]} diff --git a/challenges/interview/taxonomy/01-language-fundamentals.json b/challenges/interview/taxonomy/01-language-fundamentals.json new file mode 100644 index 0000000..e89a78a --- /dev/null +++ b/challenges/interview/taxonomy/01-language-fundamentals.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"language-fundamentals","order":1,"title":"Language fundamentals","focus":["bindings and mutability","control flow","functions and data types"],"levels":["foundation","working_rust_developer"],"references":[{"title":"Core fundamentals","path":"../../../01-core-fundamentals/README.md"}]} diff --git a/challenges/interview/taxonomy/02-ownership-and-lifetimes.json b/challenges/interview/taxonomy/02-ownership-and-lifetimes.json new file mode 100644 index 0000000..df45ba0 --- /dev/null +++ b/challenges/interview/taxonomy/02-ownership-and-lifetimes.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"ownership-and-lifetimes","order":2,"title":"Ownership and lifetimes","focus":["moves and borrows","lifetimes","API ownership choices"],"levels":["foundation","working_rust_developer","senior_rust_developer"],"references":[{"title":"Ownership and borrowing","path":"../../../06-intermediate-rust/ownership_and_borrowing/README.md"}]} diff --git a/challenges/interview/taxonomy/03-type-system.json b/challenges/interview/taxonomy/03-type-system.json new file mode 100644 index 0000000..07fed6b --- /dev/null +++ b/challenges/interview/taxonomy/03-type-system.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"type-system","order":3,"title":"Type system","focus":["enums and pattern matching","generics","traits and trait bounds"],"levels":["foundation","working_rust_developer","senior_rust_developer"],"references":[{"title":"Traits and polymorphism","path":"../../../06-intermediate-rust/traits_and_polymorphism/README.md"}]} diff --git a/challenges/interview/taxonomy/04-concurrency.json b/challenges/interview/taxonomy/04-concurrency.json new file mode 100644 index 0000000..66866ca --- /dev/null +++ b/challenges/interview/taxonomy/04-concurrency.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"concurrency","order":4,"title":"Concurrency","focus":["threads","message passing","shared-state safety"],"levels":["working_rust_developer","senior_rust_developer"],"references":[{"title":"Concurrency introduction","path":"../../../10-real-world-rust/concurrency_intro/README.md"}]} diff --git a/challenges/interview/taxonomy/05-async.json b/challenges/interview/taxonomy/05-async.json new file mode 100644 index 0000000..c239c7b --- /dev/null +++ b/challenges/interview/taxonomy/05-async.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"async","order":5,"title":"Async Rust","focus":["futures","async tasks","cancellation and borrowing"],"levels":["working_rust_developer","senior_rust_developer"],"references":[{"title":"Advanced async","path":"../../../07-advanced-concepts/advanced_async/README.md"}]} diff --git a/challenges/interview/taxonomy/06-api-design.json b/challenges/interview/taxonomy/06-api-design.json new file mode 100644 index 0000000..6c2be13 --- /dev/null +++ b/challenges/interview/taxonomy/06-api-design.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"api-design","order":6,"title":"API design","focus":["error boundaries","ownership in signatures","abstraction choices"],"levels":["working_rust_developer","senior_rust_developer"],"references":[{"title":"Error handling","path":"../../../01-core-fundamentals/error_handling/README.md"}]} diff --git a/challenges/interview/taxonomy/07-performance.json b/challenges/interview/taxonomy/07-performance.json new file mode 100644 index 0000000..c14e908 --- /dev/null +++ b/challenges/interview/taxonomy/07-performance.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"performance","order":7,"title":"Performance","focus":["allocation and data layout","measurement","algorithmic trade-offs"],"levels":["senior_rust_developer","systems_performance_specialist"],"references":[{"title":"Performance optimization","path":"../../../07-advanced-concepts/performance_optimization/README.md"}]} diff --git a/challenges/interview/taxonomy/08-unsafe-and-ffi.json b/challenges/interview/taxonomy/08-unsafe-and-ffi.json new file mode 100644 index 0000000..547d2ff --- /dev/null +++ b/challenges/interview/taxonomy/08-unsafe-and-ffi.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"unsafe-and-ffi","order":8,"title":"Unsafe and FFI","focus":["safety contracts","raw pointers","foreign-function boundaries"],"levels":["senior_rust_developer","systems_performance_specialist"],"references":[{"title":"Advanced concepts","path":"../../../07-advanced-concepts/README.md"}]} diff --git a/challenges/interview/taxonomy/09-testing-and-tooling.json b/challenges/interview/taxonomy/09-testing-and-tooling.json new file mode 100644 index 0000000..e68f9b9 --- /dev/null +++ b/challenges/interview/taxonomy/09-testing-and-tooling.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"testing-and-tooling","order":9,"title":"Testing and tooling","focus":["test design","Cargo workflows","linting and debugging"],"levels":["foundation","working_rust_developer","senior_rust_developer"],"references":[{"title":"Testing","path":"../../../03-tooling-and-quality/testing/README.md"}]} diff --git a/challenges/interview/taxonomy/10-system-design.json b/challenges/interview/taxonomy/10-system-design.json new file mode 100644 index 0000000..f2ace16 --- /dev/null +++ b/challenges/interview/taxonomy/10-system-design.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"system-design","order":10,"title":"System design","focus":["service boundaries","reliability","operational trade-offs"],"levels":["senior_rust_developer","systems_performance_specialist"],"references":[{"title":"Mini projects","path":"../../../09-mini-projects/README.md"}]} diff --git a/challenges/interview/taxonomy/11-code-review.json b/challenges/interview/taxonomy/11-code-review.json new file mode 100644 index 0000000..6c7a6fe --- /dev/null +++ b/challenges/interview/taxonomy/11-code-review.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"code-review","order":11,"title":"Code review","focus":["correctness","maintainability","idiomatic Rust"],"levels":["working_rust_developer","senior_rust_developer","systems_performance_specialist"],"references":[{"title":"Code review challenges","path":"../../code-review/README.md"}]} diff --git a/challenges/quiz-items/01-mutability-binding.json b/challenges/quiz-items/01-mutability-binding.json new file mode 100644 index 0000000..20ca392 --- /dev/null +++ b/challenges/quiz-items/01-mutability-binding.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-mutability-binding","type":"multiple_choice","topic":"variables-mutability","difficulty":"beginner","concepts":["mutability","bindings"],"question":"Which binding can be reassigned after it is created?","choices":[{"id":"a","text":"let count = 0;"},{"id":"b","text":"let mut count = 0;"},{"id":"c","text":"const COUNT: i32 = 0;"}],"answer":{"kind":"choice","value":"b"},"explanation":"Bindings are immutable by default. The `mut` keyword makes this particular binding mutable; it does not make every use of the value mutable.","references":[{"title":"Variables and mutability","path":"../../01-core-fundamentals/variables_and_mutability/README.md"}]} diff --git a/challenges/quiz-items/02-shadowing.json b/challenges/quiz-items/02-shadowing.json new file mode 100644 index 0000000..60ed58c --- /dev/null +++ b/challenges/quiz-items/02-shadowing.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-shadowing-change-type","type":"predict_output","topic":"variables-mutability","difficulty":"beginner","concepts":["shadowing","types"],"question":"What does this program print?","code":"let spaces = \" \";\nlet spaces = spaces.len();\nprintln!(\"{spaces}\");","choices":[],"answer":{"kind":"output","value":"3"},"explanation":"The second `let` creates a new binding named `spaces`. It shadows the string binding and may have a different type, so the program prints the string length.","references":[{"title":"Variables and mutability","path":"../../01-core-fundamentals/variables_and_mutability/README.md"}]} diff --git a/challenges/quiz-items/03-reassignment-type.json b/challenges/quiz-items/03-reassignment-type.json new file mode 100644 index 0000000..6185f56 --- /dev/null +++ b/challenges/quiz-items/03-reassignment-type.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-reassignment-keeps-type","type":"will_it_compile","topic":"variables-mutability","difficulty":"beginner","concepts":["mutability","types"],"question":"Will this compile?","code":"let mut label = \"start\";\nlabel = 1;","choices":[],"answer":{"kind":"compiles","value":"false"},"explanation":"`mut` permits reassignment, but it does not permit changing a binding’s type. `label` was inferred as `&str`, while `1` is an integer.","references":[{"title":"Variables and mutability","path":"../../01-core-fundamentals/variables_and_mutability/README.md"}]} diff --git a/challenges/quiz-items/04-move-after-assignment.json b/challenges/quiz-items/04-move-after-assignment.json new file mode 100644 index 0000000..f7d7d29 --- /dev/null +++ b/challenges/quiz-items/04-move-after-assignment.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-move-after-assignment","type":"will_it_compile","topic":"ownership","difficulty":"beginner","concepts":["ownership","moves","string"],"question":"Will this compile?","code":"let first = String::from(\"hello\");\nlet second = first;\nprintln!(\"{first}\");","choices":[],"answer":{"kind":"compiles","value":"false"},"explanation":"Assigning a `String` moves ownership to `second`. The original binding can no longer be used because it no longer owns the string.","references":[{"title":"Ownership","path":"../../01-core-fundamentals/ownership/README.md"}]} diff --git a/challenges/quiz-items/05-copy-after-assignment.json b/challenges/quiz-items/05-copy-after-assignment.json new file mode 100644 index 0000000..a5e6509 --- /dev/null +++ b/challenges/quiz-items/05-copy-after-assignment.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-copy-after-assignment","type":"will_it_compile","topic":"ownership","difficulty":"beginner","concepts":["ownership","copy","integers"],"question":"Will this compile?","code":"let first = 7_i32;\nlet second = first;\nprintln!(\"{first} {second}\");","choices":[],"answer":{"kind":"compiles","value":"true"},"explanation":"`i32` implements `Copy`, so assignment copies its value instead of moving ownership. Both bindings remain usable.","references":[{"title":"Ownership","path":"../../01-core-fundamentals/ownership/README.md"}]} diff --git a/challenges/quiz-items/06-clone-or-borrow.json b/challenges/quiz-items/06-clone-or-borrow.json new file mode 100644 index 0000000..6191bc4 --- /dev/null +++ b/challenges/quiz-items/06-clone-or-borrow.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-clone-or-borrow","type":"design_choice","topic":"ownership","difficulty":"beginner","concepts":["ownership","borrowing","api-design"],"question":"A function only needs to read a caller-owned `String` and must not keep it. Which parameter type is the most direct choice?","choices":[{"id":"a","text":"String"},{"id":"b","text":"&str"},{"id":"c","text":"&mut String"}],"answer":{"kind":"choice","value":"b"},"explanation":"`&str` borrows text for the duration of the call without taking ownership or requiring mutable access. Taking `String` would force a move, while `&mut String` asks for more permission than reading needs.","references":[{"title":"Ownership","path":"../../01-core-fundamentals/ownership/README.md"}]} diff --git a/challenges/quiz-items/07-immutable-borrows.json b/challenges/quiz-items/07-immutable-borrows.json new file mode 100644 index 0000000..3e04a35 --- /dev/null +++ b/challenges/quiz-items/07-immutable-borrows.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-multiple-immutable-borrows","type":"will_it_compile","topic":"ownership","difficulty":"beginner","concepts":["borrowing","references"],"question":"Will this compile?","code":"let name = String::from(\"Ada\");\nlet first = &name;\nlet second = &name;\nprintln!(\"{first} {second}\");","choices":[],"answer":{"kind":"compiles","value":"true"},"explanation":"Any number of immutable borrows may coexist. They only read the value, so they cannot create competing mutations.","references":[{"title":"Ownership","path":"../../01-core-fundamentals/ownership/README.md"}]} diff --git a/challenges/quiz-items/08-mutable-and-immutable-borrow.json b/challenges/quiz-items/08-mutable-and-immutable-borrow.json new file mode 100644 index 0000000..acb21ec --- /dev/null +++ b/challenges/quiz-items/08-mutable-and-immutable-borrow.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-mutable-immutable-borrow","type":"will_it_compile","topic":"ownership","difficulty":"beginner","concepts":["borrowing","mutable-references"],"question":"Will this compile?","code":"let mut name = String::from(\"Ada\");\nlet view = &name;\nlet edit = &mut name;\nprintln!(\"{view} {edit}\");","choices":[],"answer":{"kind":"compiles","value":"false"},"explanation":"The immutable borrow is still used in `println!`, so it overlaps with the mutable borrow. Rust permits either many readers or one writer, not both at the same time.","references":[{"title":"Ownership","path":"../../01-core-fundamentals/ownership/README.md"}]} diff --git a/challenges/quiz-items/09-borrow-instead-of-move.json b/challenges/quiz-items/09-borrow-instead-of-move.json new file mode 100644 index 0000000..3dc0bb8 --- /dev/null +++ b/challenges/quiz-items/09-borrow-instead-of-move.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-borrow-instead-of-move","type":"code_review","topic":"ownership","difficulty":"beginner","concepts":["ownership","function-parameters"],"question":"A caller needs to use `title` after calling this display-only function. What is the smallest useful API change?","code":"fn show(title: String) {\n println!(\"{title}\");\n}","choices":[],"answer":{"kind":"review","value":"Change the parameter to `&str` (or `&String`) and call the function with a borrow; `&str` is the more flexible display-only API."},"explanation":"The function does not need ownership, so accepting a borrow avoids forcing every caller to give up its `String`. `&str` also accepts string slices and string literals.","references":[{"title":"Ownership","path":"../../01-core-fundamentals/ownership/README.md"}]} diff --git a/challenges/quiz-items/10-option-match.json b/challenges/quiz-items/10-option-match.json new file mode 100644 index 0000000..d4dbcb3 --- /dev/null +++ b/challenges/quiz-items/10-option-match.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-option-match","type":"multiple_choice","topic":"result","difficulty":"beginner","concepts":["option","pattern-matching"],"question":"Which expression turns `Some(4)` into `Some(5)` and leaves `None` unchanged?","choices":[{"id":"a","text":"value.unwrap() + 1"},{"id":"b","text":"value.map(|number| number + 1)"},{"id":"c","text":"value.is_some()"}],"answer":{"kind":"choice","value":"b"},"explanation":"`Option::map` transforms the value only when it is present and preserves `None`. `unwrap` would panic on `None`, while `is_some` returns a boolean.","references":[{"title":"Option and Result handling","path":"../../02-standard-library/error_handling_basics/README.md"}]} diff --git a/challenges/quiz-items/11-option-unwrap.json b/challenges/quiz-items/11-option-unwrap.json new file mode 100644 index 0000000..21532e3 --- /dev/null +++ b/challenges/quiz-items/11-option-unwrap.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-option-unwrap-boundary","type":"design_choice","topic":"result","difficulty":"beginner","concepts":["option","error-handling"],"question":"A user-provided search may return no record. Which approach gives the caller the clearest way to handle that normal outcome?","choices":[{"id":"a","text":"Return Option"},{"id":"b","text":"Call unwrap before returning"},{"id":"c","text":"Return a fake default record"}],"answer":{"kind":"choice","value":"a"},"explanation":"Absence is part of the function’s ordinary result, so `Option` represents it directly. Panicking or inventing data hides a case the caller needs to decide about.","references":[{"title":"Option and Result handling","path":"../../02-standard-library/error_handling_basics/README.md"}]} diff --git a/challenges/quiz-items/12-option-if-let.json b/challenges/quiz-items/12-option-if-let.json new file mode 100644 index 0000000..1935c65 --- /dev/null +++ b/challenges/quiz-items/12-option-if-let.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-option-if-let","type":"predict_output","topic":"result","difficulty":"beginner","concepts":["option","if-let"],"question":"What does this program print?","code":"let score = Some(8);\nif let Some(value) = score {\n println!(\"{}\", value * 2);\n}","choices":[],"answer":{"kind":"output","value":"16"},"explanation":"`if let Some(value)` runs its body only when the option contains a value, binding the inner integer to `value`.","references":[{"title":"Option and Result handling","path":"../../02-standard-library/error_handling_basics/README.md"}]} diff --git a/challenges/quiz-items/13-option-exhaustive-match.json b/challenges/quiz-items/13-option-exhaustive-match.json new file mode 100644 index 0000000..5315648 --- /dev/null +++ b/challenges/quiz-items/13-option-exhaustive-match.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-option-exhaustive-match","type":"fix_error","topic":"result","difficulty":"beginner","concepts":["option","match","exhaustiveness"],"question":"What case must be added for this match to compile?","code":"let setting: Option<&str> = None;\nmatch setting {\n Some(value) => println!(\"{value}\"),\n}","choices":[],"answer":{"kind":"fix","value":"Add a `None` arm, such as `None => println!(\"not configured\")`."},"explanation":"A `match` on `Option` must cover both variants. Rust uses exhaustive matching to ensure the absent case is handled deliberately.","references":[{"title":"Option and Result handling","path":"../../02-standard-library/error_handling_basics/README.md"}]} diff --git a/challenges/quiz-items/14-result-question-mark.json b/challenges/quiz-items/14-result-question-mark.json new file mode 100644 index 0000000..55b3e17 --- /dev/null +++ b/challenges/quiz-items/14-result-question-mark.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-result-question-mark","type":"will_it_compile","topic":"result","difficulty":"beginner","concepts":["result","question-mark"],"question":"Will this compile?","code":"fn read_count() -> Result {\n let value: i32 = \"7\".parse().map_err(|error| error.to_string())?;\n Ok(value)\n}","choices":[],"answer":{"kind":"compiles","value":"true"},"explanation":"The `?` operator returns early with the `String` error if parsing fails. On success it yields the parsed `i32`, which is returned in `Ok`.","references":[{"title":"Option and Result handling","path":"../../02-standard-library/error_handling_basics/README.md"}]} diff --git a/challenges/quiz-items/15-result-question-mark-context.json b/challenges/quiz-items/15-result-question-mark-context.json new file mode 100644 index 0000000..6f1d4e2 --- /dev/null +++ b/challenges/quiz-items/15-result-question-mark-context.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-result-question-mark-context","type":"will_it_compile","topic":"result","difficulty":"beginner","concepts":["result","question-mark"],"question":"Will this compile?","code":"fn read_count() {\n let value: i32 = \"7\".parse()?;\n println!(\"{value}\");\n}","choices":[],"answer":{"kind":"compiles","value":"false"},"explanation":"`?` needs an enclosing function or closure that can return a compatible `Result` or `Option`. This function returns `()`, so it has nowhere to propagate the parse error.","references":[{"title":"Option and Result handling","path":"../../02-standard-library/error_handling_basics/README.md"}]} diff --git a/challenges/quiz-items/16-result-recover.json b/challenges/quiz-items/16-result-recover.json new file mode 100644 index 0000000..fdb09e2 --- /dev/null +++ b/challenges/quiz-items/16-result-recover.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-result-recover","type":"multiple_choice","topic":"result","difficulty":"beginner","concepts":["result","recovery"],"question":"Which method supplies a fallback value when a `Result` is an error?","choices":[{"id":"a","text":"unwrap_or(default)"},{"id":"b","text":"is_ok()"},{"id":"c","text":"map_err(handler)"}],"answer":{"kind":"choice","value":"a"},"explanation":"`unwrap_or` returns the success value when present and the supplied fallback on an error. `is_ok` only reports status, and `map_err` transforms the error rather than recovering a value.","references":[{"title":"Option and Result handling","path":"../../02-standard-library/error_handling_basics/README.md"}]} diff --git a/challenges/quiz-items/17-result-error-message.json b/challenges/quiz-items/17-result-error-message.json new file mode 100644 index 0000000..fbfdba2 --- /dev/null +++ b/challenges/quiz-items/17-result-error-message.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-result-error-message","type":"code_review","topic":"result","difficulty":"beginner","concepts":["result","error-context"],"question":"Why is this API misleading when an input can be malformed, and what should it return instead?","code":"fn parse_port(text: &str) -> u16 {\n text.parse().unwrap()\n}","choices":[],"answer":{"kind":"review","value":"It panics for ordinary invalid input; return `Result` (or a domain error type) so the caller can handle the parse failure."},"explanation":"Malformed user input is an expected operational outcome, not necessarily a programmer bug. Returning `Result` preserves the error and lets the caller choose a response.","references":[{"title":"Option and Result handling","path":"../../02-standard-library/error_handling_basics/README.md"}]} diff --git a/challenges/quiz-items/18-result-map.json b/challenges/quiz-items/18-result-map.json new file mode 100644 index 0000000..057216a --- /dev/null +++ b/challenges/quiz-items/18-result-map.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-result-map","type":"predict_output","topic":"result","difficulty":"beginner","concepts":["result","map"],"question":"What does this program print?","code":"let value: Result = Ok(3);\nlet doubled = value.map(|number| number * 2);\nprintln!(\"{doubled:?}\");","choices":[],"answer":{"kind":"output","value":"Ok(6)"},"explanation":"`Result::map` transforms the success value and preserves the error variant. Here it applies the closure to `3` and produces `Ok(6)`.","references":[{"title":"Option and Result handling","path":"../../02-standard-library/error_handling_basics/README.md"}]} diff --git a/challenges/quiz-items/19-option-or-result.json b/challenges/quiz-items/19-option-or-result.json new file mode 100644 index 0000000..014935d --- /dev/null +++ b/challenges/quiz-items/19-option-or-result.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-option-or-result","type":"design_choice","topic":"result","difficulty":"beginner","concepts":["option","result","api-design"],"question":"A configuration lookup can either find a key, fail because the configuration file cannot be read, or find no matching key. Which return type preserves all three outcomes?","choices":[{"id":"a","text":"Option"},{"id":"b","text":"Result, ConfigError>"},{"id":"c","text":"String"}],"answer":{"kind":"choice","value":"b"},"explanation":"The outer `Result` distinguishes a read failure from success. On successful reading, the inner `Option` distinguishes a missing key from a present value.","references":[{"title":"Option and Result handling","path":"../../02-standard-library/error_handling_basics/README.md"}]} diff --git a/challenges/quiz-items/20-borrow-and-option.json b/challenges/quiz-items/20-borrow-and-option.json new file mode 100644 index 0000000..6e627dc --- /dev/null +++ b/challenges/quiz-items/20-borrow-and-option.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-borrow-option-as-deref","type":"fix_error","topic":"ownership","difficulty":"intermediate","concepts":["borrowing","option","as-deref"],"question":"How can this function return a borrowed string slice without moving the `String` out of the option?","code":"fn label(value: &Option) -> Option<&str> {\n value.map(|text| text.as_str())\n}","choices":[],"answer":{"kind":"fix","value":"Use `value.as_deref()` or `value.as_ref().map(String::as_str)` so the function maps over a borrow instead of trying to move from `&Option`."},"explanation":"Calling `map` directly on `&Option` tries to use the by-value `Option::map` method. `as_deref` converts the borrowed option into `Option<&str>` without moving the owned string.","references":[{"title":"Ownership","path":"../../01-core-fundamentals/ownership/README.md"},{"title":"Option and Result handling","path":"../../02-standard-library/error_handling_basics/README.md"}]} diff --git a/challenges/quiz-items/21-explicit-type.json b/challenges/quiz-items/21-explicit-type.json new file mode 100644 index 0000000..76e155e --- /dev/null +++ b/challenges/quiz-items/21-explicit-type.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-explicit-type-annotation","type":"multiple_choice","topic":"data-types","difficulty":"beginner","concepts":["type-annotations","inference"],"question":"Which declaration explicitly stores the value as an unsigned 8-bit integer?","choices":[{"id":"a","text":"let count: u8 = 12;"},{"id":"b","text":"let count = u8;"},{"id":"c","text":"let count: unsigned = 12;"}],"answer":{"kind":"choice","value":"a"},"explanation":"A colon after the binding name introduces a type annotation. `u8` is Rust’s unsigned eight-bit integer type.","references":[{"title":"Data types","path":"../../01-core-fundamentals/data_types/README.md"}]} diff --git a/challenges/quiz-items/22-if-expression.json b/challenges/quiz-items/22-if-expression.json new file mode 100644 index 0000000..92b9270 --- /dev/null +++ b/challenges/quiz-items/22-if-expression.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-if-is-expression","type":"predict_output","topic":"control-flow","difficulty":"beginner","concepts":["if-expressions","control-flow"],"question":"What does this program print?","code":"let temperature = 18;\nlet label = if temperature < 20 { \"cool\" } else { \"warm\" };\nprintln!(\"{label}\");","choices":[],"answer":{"kind":"output","value":"cool"},"explanation":"`if` is an expression in Rust, so each branch can produce the value assigned to `label`.","references":[{"title":"Control flow","path":"../../01-core-fundamentals/control_flow/README.md"}]} diff --git a/challenges/quiz-items/23-tuple-destructure.json b/challenges/quiz-items/23-tuple-destructure.json new file mode 100644 index 0000000..2dc5064 --- /dev/null +++ b/challenges/quiz-items/23-tuple-destructure.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-tuple-destructure","type":"predict_output","topic":"data-types","difficulty":"beginner","concepts":["tuples","destructuring"],"question":"What does this program print?","code":"let point = (3, 5);\nlet (x, y) = point;\nprintln!(\"{}\", x + y);","choices":[],"answer":{"kind":"output","value":"8"},"explanation":"The tuple pattern assigns its first and second values to `x` and `y`, which are then added.","references":[{"title":"Data types","path":"../../01-core-fundamentals/data_types/README.md"}]} diff --git a/challenges/quiz-items/24-range-loop.json b/challenges/quiz-items/24-range-loop.json new file mode 100644 index 0000000..c4cd7ae --- /dev/null +++ b/challenges/quiz-items/24-range-loop.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-exclusive-range-loop","type":"predict_output","topic":"control-flow","difficulty":"beginner","concepts":["loops","ranges"],"question":"What does this program print?","code":"let mut total = 0;\nfor number in 1..4 {\n total += number;\n}\nprintln!(\"{total}\");","choices":[],"answer":{"kind":"output","value":"6"},"explanation":"The range `1..4` includes 1, 2, and 3 but excludes 4, so the total is 6.","references":[{"title":"Control flow","path":"../../01-core-fundamentals/control_flow/README.md"}]} diff --git a/challenges/quiz-items/25-function-return.json b/challenges/quiz-items/25-function-return.json new file mode 100644 index 0000000..a5831b2 --- /dev/null +++ b/challenges/quiz-items/25-function-return.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-function-return-expression","type":"multiple_choice","topic":"functions","difficulty":"beginner","concepts":["functions","return-values"],"question":"Which final line makes this function return `number + 1` without using `return`?","choices":[{"id":"a","text":"number + 1"},{"id":"b","text":"number + 1;"},{"id":"c","text":"println!(\"{}\", number + 1);"}],"answer":{"kind":"choice","value":"a"},"explanation":"The final expression without a semicolon is returned from a function. Adding a semicolon turns it into a statement with the unit value `()`.","references":[{"title":"Functions","path":"../../01-core-fundamentals/functions/README.md"}]} diff --git a/challenges/quiz-items/26-match-boolean.json b/challenges/quiz-items/26-match-boolean.json new file mode 100644 index 0000000..5a4dd69 --- /dev/null +++ b/challenges/quiz-items/26-match-boolean.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-match-boolean","type":"predict_output","topic":"control-flow","difficulty":"beginner","concepts":["match","booleans"],"question":"What does this program print?","code":"let ready = true;\nlet message = match ready {\n true => \"go\",\n false => \"wait\",\n};\nprintln!(\"{message}\");","choices":[],"answer":{"kind":"output","value":"go"},"explanation":"The `true` arm matches and produces the string assigned to `message`.","references":[{"title":"Control flow","path":"../../01-core-fundamentals/control_flow/README.md"}]} diff --git a/challenges/quiz-items/27-char-or-str.json b/challenges/quiz-items/27-char-or-str.json new file mode 100644 index 0000000..a203d2c --- /dev/null +++ b/challenges/quiz-items/27-char-or-str.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-char-or-str","type":"multiple_choice","topic":"data-types","difficulty":"beginner","concepts":["characters","strings"],"question":"Which literal has the Rust type `char`?","choices":[{"id":"a","text":"'R'"},{"id":"b","text":"\"R\""},{"id":"c","text":"r#\"R\"#"}],"answer":{"kind":"choice","value":"a"},"explanation":"Single quotes create a Unicode scalar `char`; double quotes create a string slice. Raw string syntax still creates a string slice.","references":[{"title":"Data types","path":"../../01-core-fundamentals/data_types/README.md"}]} diff --git a/challenges/quiz-items/28-clone-keeps-owner.json b/challenges/quiz-items/28-clone-keeps-owner.json new file mode 100644 index 0000000..6efd318 --- /dev/null +++ b/challenges/quiz-items/28-clone-keeps-owner.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-clone-keeps-owner","type":"will_it_compile","topic":"ownership","difficulty":"beginner","concepts":["ownership","clone","string"],"question":"Will this compile?","code":"let first = String::from(\"hello\");\nlet second = first.clone();\nprintln!(\"{first} {second}\");","choices":[],"answer":{"kind":"compiles","value":"true"},"explanation":"`clone` creates a separate owned `String`, so `first` remains valid and both values can be used.","references":[{"title":"Ownership","path":"../../01-core-fundamentals/ownership/README.md"}]} diff --git a/challenges/quiz-items/29-mutable-reference-update.json b/challenges/quiz-items/29-mutable-reference-update.json new file mode 100644 index 0000000..b5720f2 --- /dev/null +++ b/challenges/quiz-items/29-mutable-reference-update.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-mutable-reference-update","type":"will_it_compile","topic":"ownership","difficulty":"beginner","concepts":["borrowing","mutable-references"],"question":"Will this compile?","code":"fn add_mark(text: &mut String) {\n text.push('!');\n}\n\nfn main() {\n let mut text = String::from(\"ready\");\n add_mark(&mut text);\n println!(\"{text}\");\n}","choices":[],"answer":{"kind":"compiles","value":"true"},"explanation":"The caller declares the binding mutable and passes one mutable borrow. The function may mutate through that borrow, and the borrow ends after the call.","references":[{"title":"Ownership","path":"../../01-core-fundamentals/ownership/README.md"}]} diff --git a/challenges/quiz-items/30-borrow-ends-after-use.json b/challenges/quiz-items/30-borrow-ends-after-use.json new file mode 100644 index 0000000..98caeaa --- /dev/null +++ b/challenges/quiz-items/30-borrow-ends-after-use.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-borrow-ends-after-use","type":"will_it_compile","topic":"ownership","difficulty":"intermediate","concepts":["borrowing","non-lexical-lifetimes"],"question":"Will this compile?","code":"let mut name = String::from(\"Ada\");\nlet view = &name;\nprintln!(\"{view}\");\nname.push('!');","choices":[],"answer":{"kind":"compiles","value":"true"},"explanation":"The immutable borrow is last used by `println!`. Rust’s non-lexical lifetime analysis lets the later mutation proceed after that use.","references":[{"title":"Ownership and borrowing","path":"../../06-intermediate-rust/ownership_and_borrowing/README.md"}]} diff --git a/challenges/quiz-items/31-vector-move.json b/challenges/quiz-items/31-vector-move.json new file mode 100644 index 0000000..0f6f6de --- /dev/null +++ b/challenges/quiz-items/31-vector-move.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-vector-move","type":"will_it_compile","topic":"ownership","difficulty":"beginner","concepts":["ownership","vectors","moves"],"question":"Will this compile?","code":"let numbers = vec![1, 2, 3];\nlet saved = numbers;\nprintln!(\"{numbers:?}\");","choices":[],"answer":{"kind":"compiles","value":"false"},"explanation":"A `Vec` owns its allocation and does not implement `Copy`. Assigning it moves ownership to `saved`, leaving `numbers` unavailable.","references":[{"title":"Ownership","path":"../../01-core-fundamentals/ownership/README.md"}]} diff --git a/challenges/quiz-items/32-slice-does-not-own.json b/challenges/quiz-items/32-slice-does-not-own.json new file mode 100644 index 0000000..e7828b2 --- /dev/null +++ b/challenges/quiz-items/32-slice-does-not-own.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-slice-does-not-own","type":"design_choice","topic":"ownership","difficulty":"beginner","concepts":["slices","borrowing","api-design"],"question":"A function needs to read the first word of a `String` without allocating or taking ownership. Which return type best expresses that result?","choices":[{"id":"a","text":"String"},{"id":"b","text":"&str"},{"id":"c","text":"&mut str"}],"answer":{"kind":"choice","value":"b"},"explanation":"A string slice borrows the relevant text from the caller’s string. Returning `String` would allocate or move owned data, and a mutable slice is unnecessary for reading.","references":[{"title":"Ownership","path":"../../01-core-fundamentals/ownership/README.md"}]} diff --git a/challenges/quiz-items/33-reference-pattern.json b/challenges/quiz-items/33-reference-pattern.json new file mode 100644 index 0000000..02743ae --- /dev/null +++ b/challenges/quiz-items/33-reference-pattern.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-reference-pattern","type":"predict_output","topic":"ownership","difficulty":"beginner","concepts":["references","patterns"],"question":"What does this program print?","code":"let value = 9;\nlet reference = &value;\nlet &copied = reference;\nprintln!(\"{copied}\");","choices":[],"answer":{"kind":"output","value":"9"},"explanation":"The `&copied` pattern matches the reference and copies the inner `i32` into `copied`.","references":[{"title":"Ownership and borrowing","path":"../../06-intermediate-rust/ownership_and_borrowing/README.md"}]} diff --git a/challenges/quiz-items/34-return-owner.json b/challenges/quiz-items/34-return-owner.json new file mode 100644 index 0000000..cd0dfb3 --- /dev/null +++ b/challenges/quiz-items/34-return-owner.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-return-owner","type":"design_choice","topic":"ownership","difficulty":"beginner","concepts":["ownership","function-returns"],"question":"A function takes a `String`, changes it, and the caller needs the changed string afterward. Which signature makes ownership transfer explicit without borrowing?","choices":[{"id":"a","text":"fn edit(text: String) -> String"},{"id":"b","text":"fn edit(text: String)"},{"id":"c","text":"fn edit(text: &String) -> String"}],"answer":{"kind":"choice","value":"a"},"explanation":"Taking and returning `String` clearly transfers ownership into and back out of the function. A mutable borrow can also be appropriate, but option A states the requested ownership-transfer design.","references":[{"title":"Ownership","path":"../../01-core-fundamentals/ownership/README.md"}]} diff --git a/challenges/quiz-items/35-string-literal-borrow.json b/challenges/quiz-items/35-string-literal-borrow.json new file mode 100644 index 0000000..ed44d14 --- /dev/null +++ b/challenges/quiz-items/35-string-literal-borrow.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-string-literal-borrow","type":"multiple_choice","topic":"ownership","difficulty":"beginner","concepts":["string-slices","borrowing"],"question":"Which value can be passed directly to a parameter of type `&str` without allocation?","choices":[{"id":"a","text":"\"hello\""},{"id":"b","text":"String::from(\"hello\") only after cloning"},{"id":"c","text":"A `Vec`"}],"answer":{"kind":"choice","value":"a"},"explanation":"A string literal already has type `&'static str`, so it can be used wherever a borrowed string slice is accepted.","references":[{"title":"Ownership","path":"../../01-core-fundamentals/ownership/README.md"}]} diff --git a/challenges/quiz-items/36-generic-identity.json b/challenges/quiz-items/36-generic-identity.json new file mode 100644 index 0000000..1b5ce43 --- /dev/null +++ b/challenges/quiz-items/36-generic-identity.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-generic-identity","type":"will_it_compile","topic":"generics","difficulty":"beginner","concepts":["generics","functions"],"question":"Will this compile?","code":"fn identity(value: T) -> T {\n value\n}\n\nfn main() {\n println!(\"{}\", identity(4));\n}","choices":[],"answer":{"kind":"compiles","value":"true"},"explanation":"The generic type parameter `T` lets the function accept and return the same concrete type. Here Rust infers `T` as `i32`.","references":[{"title":"Generics","path":"../../06-intermediate-rust/generics/README.md"}]} diff --git a/challenges/quiz-items/37-generic-display-bound.json b/challenges/quiz-items/37-generic-display-bound.json new file mode 100644 index 0000000..8d688e8 --- /dev/null +++ b/challenges/quiz-items/37-generic-display-bound.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-generic-display-bound","type":"will_it_compile","topic":"generics","difficulty":"beginner","concepts":["generics","trait-bounds"],"question":"Will this compile?","code":"fn show(value: T) {\n println!(\"{value}\");\n}","choices":[],"answer":{"kind":"compiles","value":"false"},"explanation":"Formatting `value` with `{value}` requires the `Display` trait, but an unconstrained `T` is not guaranteed to implement it. Add a `T: std::fmt::Display` bound.","references":[{"title":"Generics","path":"../../06-intermediate-rust/generics/README.md"}]} diff --git a/challenges/quiz-items/38-trait-implementation.json b/challenges/quiz-items/38-trait-implementation.json new file mode 100644 index 0000000..55451d8 --- /dev/null +++ b/challenges/quiz-items/38-trait-implementation.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-trait-implementation","type":"fix_error","topic":"traits","difficulty":"beginner","concepts":["traits","implementations"],"question":"What must be added so `announce(&task)` can call `describe`?","code":"trait Describable {\n fn describe(&self) -> String;\n}\n\nstruct Task;\n\nfn announce(item: &impl Describable) {\n println!(\"{}\", item.describe());\n}","choices":[],"answer":{"kind":"fix","value":"Add `impl Describable for Task` with a `describe` method, then create `Task` and pass a reference to it."},"explanation":"Defining a trait does not automatically make a type implement it. The explicit `impl` block supplies the behaviour required by the function’s bound.","references":[{"title":"Traits and polymorphism","path":"../../06-intermediate-rust/traits_and_polymorphism/README.md"}]} diff --git a/challenges/quiz-items/39-enum-state.json b/challenges/quiz-items/39-enum-state.json new file mode 100644 index 0000000..38d2091 --- /dev/null +++ b/challenges/quiz-items/39-enum-state.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-enum-state","type":"design_choice","topic":"enums-pattern-matching","difficulty":"beginner","concepts":["enums","state-modeling"],"question":"A network request is exactly one of pending, successful with text, or failed with an error message. Which Rust representation makes those exclusive states clearest?","choices":[{"id":"a","text":"An enum with Pending, Success(String), and Failed(String) variants"},{"id":"b","text":"Three unrelated booleans"},{"id":"c","text":"A nullable string and a separate error string"}],"answer":{"kind":"choice","value":"a"},"explanation":"An enum encodes the valid alternatives in one type and lets `match` handle each case explicitly. Independent flags can represent contradictory states.","references":[{"title":"Enums and pattern matching","path":"../../06-intermediate-rust/enums_and_pattern_matching/README.md"}]} diff --git a/challenges/quiz-items/40-derived-debug.json b/challenges/quiz-items/40-derived-debug.json new file mode 100644 index 0000000..8e5d986 --- /dev/null +++ b/challenges/quiz-items/40-derived-debug.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-derived-debug","type":"fix_error","topic":"traits","difficulty":"beginner","concepts":["derive","debug"],"question":"What attribute should be added above this struct so `println!(\"{item:?}\")` can format it for debugging?","code":"struct Item {\n id: u32,\n}","choices":[],"answer":{"kind":"fix","value":"Add `#[derive(Debug)]` above `struct Item`."},"explanation":"The `:?` formatter needs `Debug`. For a simple struct, deriving that standard trait is the direct solution.","references":[{"title":"Traits and polymorphism","path":"../../06-intermediate-rust/traits_and_polymorphism/README.md"}]} diff --git a/challenges/quiz-items/41-trait-default-method.json b/challenges/quiz-items/41-trait-default-method.json new file mode 100644 index 0000000..78cfd24 --- /dev/null +++ b/challenges/quiz-items/41-trait-default-method.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-trait-default-method","type":"will_it_compile","topic":"traits","difficulty":"beginner","concepts":["traits","default-methods"],"question":"Will this compile?","code":"trait Greet {\n fn message(&self) -> String {\n String::from(\"hello\")\n }\n}\n\nstruct Person;\nimpl Greet for Person {}\n\nfn main() {\n println!(\"{}\", Person.message());\n}","choices":[],"answer":{"kind":"compiles","value":"true"},"explanation":"A trait can provide a default method body. `Person` implements the trait without overriding it, so it receives the default `message` method.","references":[{"title":"Traits and polymorphism","path":"../../06-intermediate-rust/traits_and_polymorphism/README.md"}]} diff --git a/challenges/quiz-items/42-impl-trait-return.json b/challenges/quiz-items/42-impl-trait-return.json new file mode 100644 index 0000000..e1f4e80 --- /dev/null +++ b/challenges/quiz-items/42-impl-trait-return.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-impl-trait-return","type":"multiple_choice","topic":"traits","difficulty":"intermediate","concepts":["traits","impl-trait"],"question":"What does `-> impl Iterator` communicate about a function result?","choices":[{"id":"a","text":"It returns one concrete hidden type that implements the stated iterator trait"},{"id":"b","text":"It can return unrelated iterator types from any branch"},{"id":"c","text":"It returns a trait value with no concrete type"}],"answer":{"kind":"choice","value":"a"},"explanation":"`impl Trait` in return position hides one concrete return type while promising the listed trait interface. Branches must still agree on that concrete type.","references":[{"title":"Traits and polymorphism","path":"../../06-intermediate-rust/traits_and_polymorphism/README.md"}]} diff --git a/challenges/quiz-items/43-enum-payload.json b/challenges/quiz-items/43-enum-payload.json new file mode 100644 index 0000000..777fdcb --- /dev/null +++ b/challenges/quiz-items/43-enum-payload.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-enum-payload","type":"predict_output","topic":"enums-pattern-matching","difficulty":"beginner","concepts":["enums","pattern-matching"],"question":"What does this program print?","code":"enum Message {\n Move { x: i32, y: i32 },\n}\n\nlet message = Message::Move { x: 2, y: 3 };\nmatch message {\n Message::Move { x, y } => println!(\"{}\", x * y),\n}","choices":[],"answer":{"kind":"output","value":"6"},"explanation":"The match pattern extracts the two named fields from the `Move` variant and multiplies them.","references":[{"title":"Enums and pattern matching","path":"../../06-intermediate-rust/enums_and_pattern_matching/README.md"}]} diff --git a/challenges/quiz-items/44-where-clause.json b/challenges/quiz-items/44-where-clause.json new file mode 100644 index 0000000..0b5cdd8 --- /dev/null +++ b/challenges/quiz-items/44-where-clause.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-where-clause","type":"multiple_choice","topic":"generics","difficulty":"intermediate","concepts":["generics","where-clauses"],"question":"Why might an author use a `where` clause on a generic function?","choices":[{"id":"a","text":"To place several trait bounds where a long signature stays readable"},{"id":"b","text":"To bypass trait bounds"},{"id":"c","text":"To make every generic type dynamically dispatched"}],"answer":{"kind":"choice","value":"a"},"explanation":"A `where` clause is alternate syntax for bounds. It is especially useful when bounds are numerous or include associated-type constraints.","references":[{"title":"Generics","path":"../../06-intermediate-rust/generics/README.md"}]} diff --git a/challenges/quiz-items/45-derive-partial-eq.json b/challenges/quiz-items/45-derive-partial-eq.json new file mode 100644 index 0000000..0d475c9 --- /dev/null +++ b/challenges/quiz-items/45-derive-partial-eq.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-derived-partial-eq","type":"fix_error","topic":"traits","difficulty":"beginner","concepts":["derive","partial-eq"],"question":"What trait should this simple struct derive so two values can be compared with `==`?","code":"struct Point {\n x: i32,\n y: i32,\n}","choices":[],"answer":{"kind":"fix","value":"Add `#[derive(PartialEq)]` above `struct Point`."},"explanation":"The equality operator requires `PartialEq`. For a struct whose fields already support equality, deriving it supplies the usual field-by-field comparison.","references":[{"title":"Common traits","path":"../../02-standard-library/common_traits/README.md"}]} diff --git a/challenges/quiz-items/46-cargo-check.json b/challenges/quiz-items/46-cargo-check.json new file mode 100644 index 0000000..a613f7e --- /dev/null +++ b/challenges/quiz-items/46-cargo-check.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-cargo-check","type":"multiple_choice","topic":"tooling","difficulty":"beginner","concepts":["cargo","compilation"],"question":"Which Cargo command type-checks a package without producing a runnable release binary?","choices":[{"id":"a","text":"cargo check"},{"id":"b","text":"cargo run"},{"id":"c","text":"cargo clean"}],"answer":{"kind":"choice","value":"a"},"explanation":"`cargo check` performs the compiler checks needed to find type and borrow errors while avoiding the final code-generation work needed for a normal build.","references":[{"title":"Tooling and quality","path":"../../03-tooling-and-quality/README.md"}]} diff --git a/challenges/quiz-items/47-cargo-test.json b/challenges/quiz-items/47-cargo-test.json new file mode 100644 index 0000000..f678a27 --- /dev/null +++ b/challenges/quiz-items/47-cargo-test.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-cargo-test","type":"multiple_choice","topic":"tooling","difficulty":"beginner","concepts":["cargo","testing"],"question":"Which command compiles and runs the test functions marked with `#[test]`?","choices":[{"id":"a","text":"cargo test"},{"id":"b","text":"cargo fmt"},{"id":"c","text":"cargo doc"}],"answer":{"kind":"choice","value":"a"},"explanation":"`cargo test` builds the test targets and executes their test functions. Formatting and documentation commands do not run tests.","references":[{"title":"Testing","path":"../../03-tooling-and-quality/testing/README.md"}]} diff --git a/challenges/quiz-items/48-rustfmt.json b/challenges/quiz-items/48-rustfmt.json new file mode 100644 index 0000000..fbe4147 --- /dev/null +++ b/challenges/quiz-items/48-rustfmt.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-rustfmt-command","type":"design_choice","topic":"tooling","difficulty":"beginner","concepts":["cargo","formatting"],"question":"Before opening a pull request that changes Rust source, which command is the usual project-wide formatting step?","choices":[{"id":"a","text":"cargo fmt"},{"id":"b","text":"cargo fix --broken-code"},{"id":"c","text":"cargo clean"}],"answer":{"kind":"choice","value":"a"},"explanation":"`cargo fmt` applies Rustfmt’s standard formatting. It is a predictable, low-risk preparation step before review.","references":[{"title":"Code quality tools","path":"../../03-tooling-and-quality/code_quality_tools/README.md"}]} diff --git a/challenges/quiz-items/49-clippy.json b/challenges/quiz-items/49-clippy.json new file mode 100644 index 0000000..3e3adb8 --- /dev/null +++ b/challenges/quiz-items/49-clippy.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-clippy-purpose","type":"multiple_choice","topic":"tooling","difficulty":"beginner","concepts":["clippy","linting"],"question":"What is Cargo Clippy primarily for?","choices":[{"id":"a","text":"Finding likely mistakes and non-idiomatic Rust through lints"},{"id":"b","text":"Resolving every dependency version automatically"},{"id":"c","text":"Publishing a crate"}],"answer":{"kind":"choice","value":"a"},"explanation":"Clippy is Rust’s lint collection for patterns that may be wrong, inefficient, or less idiomatic. It complements compilation and tests.","references":[{"title":"Code quality tools","path":"../../03-tooling-and-quality/code_quality_tools/README.md"}]} diff --git a/challenges/quiz-items/50-cargo-manifest.json b/challenges/quiz-items/50-cargo-manifest.json new file mode 100644 index 0000000..1d62dab --- /dev/null +++ b/challenges/quiz-items/50-cargo-manifest.json @@ -0,0 +1 @@ +{"schema_version":1,"id":"quiz-cargo-manifest","type":"multiple_choice","topic":"tooling","difficulty":"beginner","concepts":["cargo","manifest","dependencies"],"question":"Which file declares a Rust package’s name, edition, and dependencies for Cargo?","choices":[{"id":"a","text":"Cargo.toml"},{"id":"b","text":"Cargo.lock"},{"id":"c","text":"rustfmt.toml"}],"answer":{"kind":"choice","value":"a"},"explanation":"`Cargo.toml` is the package manifest. `Cargo.lock` records resolved dependency versions, while `rustfmt.toml` configures formatting when present.","references":[{"title":"Tooling and quality","path":"../../03-tooling-and-quality/README.md"}]} diff --git a/challenges/will-it-compile/README.md b/challenges/will-it-compile/README.md new file mode 100644 index 0000000..77fac8f --- /dev/null +++ b/challenges/will-it-compile/README.md @@ -0,0 +1,7 @@ +# Will It Compile? + +These challenges ask you to decide whether a short Rust program is accepted by the compiler before you run it. The useful part is the reasoning: identify ownership, borrowing, trait, lifetime, or type rules that apply, then explain the compiler’s decision in your own words. + +The current questions are structured quiz items, not a second copy of the core lessons. Start with the `will_it_compile` items in [quiz-items/](../quiz-items/), reveal the answer only after making a prediction, and follow the item’s canonical lesson reference when you need a refresher. + +When authoring one of these challenges, include the smallest complete code sample that demonstrates the rule. Validate both the expected compiler result and the explanation. A compilation failure should be intentional and should teach one primary idea rather than becoming a puzzle about unrelated syntax. diff --git a/docs/authoring/content-rubric.md b/docs/authoring/content-rubric.md new file mode 100644 index 0000000..bbbbeca --- /dev/null +++ b/docs/authoring/content-rubric.md @@ -0,0 +1,25 @@ +# Content rubric + +This rubric is the human review required before a topic can become Stable. It is deliberately separate from `contentctl`: automation can prove that declared files and metadata are internally consistent, but it cannot decide whether an explanation is accurate, proportionate, or useful to a learner. + +## Use the rubric + +Review the topic in its rendered form and run every command that applies to its examples and exercises. Record `validation.content_rubric` as `passed` only when every applicable criterion below passes and the reviewer can point to the supporting material in the same change. Until then, keep it `pending`; do not promote a topic because its metadata parses or one example compiles. + +## Required criteria + +- Scope: The title, objectives, prerequisites, level, and estimated time describe the material the learner actually receives. +- Explanation: The lesson states the mental model before relying on terminology, distinguishes closely related concepts, and does not make claims that its examples contradict. +- Examples: Each example is focused on the stated objective, is runnable or has a documented environment-specific gate, and has been checked with that gate. +- Practice: Applicable practice has a clear learner task and a verifiable result. If practice is deliberately not applicable, the topic explains why; a missing exercise is not a reason to mark it not applicable. +- Navigation: Links resolve, prerequisites are truthful, and canonical material is linked instead of copied into transition tracks. +- Safety and maintenance: Commands do not require undisclosed credentials or destructive setup, and the material avoids version-specific claims unless they are documented. +- Voice: The page uses direct learner-facing language, does not overclaim completeness, and keeps Markdown prose unwrapped in source. + +## Automation boundary + +`contentctl validate .` checks metadata shape, stable IDs, prerequisite rules, and the prohibition on publishing non-Stable material. Module and package commands supply the executable evidence named by `validation.examples` and `validation.exercises`. A successful run of those checks is necessary evidence, but the rubric review is still required before `status` can be `stable`. + +## Evidence record + +In a content change, include the commands run and the reviewed files in the pull request description or other project-approved review record. Do not add private agent logs or working notes to this repository. The metadata should report only the resulting evidence state, not a claim that a future reviewer still needs to verify. diff --git a/docs/authoring/topic-guide.md b/docs/authoring/topic-guide.md new file mode 100644 index 0000000..fe214ee --- /dev/null +++ b/docs/authoring/topic-guide.md @@ -0,0 +1,72 @@ +# Topic authoring guide + +This guide describes how to add or revise a learning topic without weakening the curriculum structure. A topic should teach one coherent idea, provide enough evidence for its public status, and remain usable from both the repository and the future website. + +## Choose the topic boundary first + +A topic needs a clear learner outcome that can be completed and reviewed as one unit. “Use `Result` to represent and propagate recoverable errors” is a topic; “error handling” may be a module containing several topics. Split material when its prerequisites, level, exercises, or validation requirements differ enough that learners should encounter it separately. + +Before creating a directory, search the repository for the same concept. Extend the canonical topic when it already exists. Translation tracks should link to canonical Rust explanations and add language-transfer context rather than copying the lesson. + +Do not move or rename an existing topic merely to make its current path match a preferred structure. Stable metadata IDs are independent of paths, and structural normalization is handled as a separate reviewed change. + +## Recommended topic contents + +A complete topic normally contains a `README.md`, focused examples, practice work, and `metadata.json`. Larger topics may add a mental model, key takeaways, or separate concept notes. Include only files that serve the learner; empty scaffolds do not count as completed material. + +Runnable examples should be small enough to expose the idea being taught. Add tests when behavior matters, and use compile-fail validation for intentionally broken examples once that harness is available. Do not silence warnings just to pass checks unless the warning itself is part of the lesson. + +## Write the metadata + +Use the [version 1 metadata contract](../content-metadata.md), the [content rubric](content-rubric.md), and the [documented example](../examples/topic-metadata.json). Place the finished file at `metadata.json` in the topic directory. + +- Give the topic a lowercase kebab-case `id` that describes the concept rather than its current directory. Treat that ID as permanent once prerequisite links or exports depend on it. +- Choose the public `status` from [CONTENT_STATUS.md](../../CONTENT_STATUS.md) and record only evidence that exists in the repository today. +- Use `prerequisites` for stable topic IDs, not paths or display titles. A prerequisite may be pending migration during the pilot, but it must still use its intended stable ID. `contentctl validate` reports an unresolved ID without failing an unpublished topic; publication requires metadata for every listed prerequisite in the validation scope. +- Keep `concepts` specific enough to support navigation and search. Prefer `move-semantics` over broad tags such as `programming`. +- List every applicable learner `track`, using `core` for the canonical curriculum and language names only when the same topic is intentionally part of those journeys. +- Write concrete `learning_objectives` that describe what a learner can explain, predict, implement, or debug after completing the topic. +- Base `estimated_minutes` on reading, running examples, and completing applicable practice rather than reading time alone. +- Keep `website.published` false until the topic is Stable. Website order controls presentation later and does not determine curriculum correctness. +- Mark rubric, example, and exercise evidence as `passed` only when the corresponding review or automated check has actually passed. Use `pending` for unfinished evidence and `not_applicable` only when the topic deliberately does not need that form of evidence. + +Exercise evidence may come from a module-level exercise that is clearly mapped to the topic; it does not require a topic-local `exercises` directory. The absence of that directory is not enough to claim `not_applicable`. Use `pending` when practice is promised, exists without an automated check, or has not yet been mapped and validated. + +## Apply status honestly + +Planned means the intended topic is visible but substantive learning material or implementation is missing. Draft means useful material exists but known gaps remain. Review means the material is usable and all currently applicable repository checks pass, while the formal rubric may still be pending. + +Stable is deliberately difficult to reach. The content rubric must pass, examples and exercises must pass their applicable automated validation or be explicitly not applicable, and the metadata validator must accept the topic. Passing the metadata schema alone never promotes content. + +When a status changes, update `CONTENT_STATUS.md` in the same change and state the supporting commands. A failed correctness check or newly discovered teaching problem moves content back to Draft until it is resolved. + +## Validate the topic + +Validate one metadata file while editing it: + +```bash +cargo run --manifest-path tools/contentctl/Cargo.toml -- validate path/to/topic/metadata.json +``` + +Validate all migrated topics and inspect their deterministic export from the repository root: + +```bash +cargo run --manifest-path tools/contentctl/Cargo.toml -- validate . +cargo run --manifest-path tools/contentctl/Cargo.toml -- export . +``` + +Run the topic's own formatting, lint, compilation, and test commands as well. Use `make check` for modules that provide it and the Cargo commands documented in `CONTRIBUTING.md` for standalone packages. Target-specific, database-backed, and hardware examples must use their documented gates instead of pretending a host-only check proves runtime behavior. + +## Keep repository and website responsibilities separate + +The learning repository remains the canonical source for topic metadata and lesson bodies. The website consumes a deterministic export and renders that source; it must not maintain a second hand-edited copy of the curriculum. Do not add Astro files, Vercel configuration, generated website records, or private coordination material to a topic directory. + +Generated exports are disposable build artifacts. Review changes to source metadata and lessons, then regenerate downstream data when needed. + +## Write for people + +Use direct explanations, concrete examples, and terminology that matches the learner's level. Remove generic introductions, repetitive summaries, inflated claims, and narration about how the material was produced. + +Do not hard-wrap Markdown prose at a fixed column. Keep each paragraph and list item on one physical source line and let the renderer wrap it. Preserve deliberate boundaries in headings, tables, quotations, and code blocks. + +Before requesting review, read the rendered page, run the documented commands, confirm every link and prerequisite, and compare the metadata claims with the files that actually exist. diff --git a/docs/challenge-scoring.md b/docs/challenge-scoring.md new file mode 100644 index 0000000..478f6fc --- /dev/null +++ b/docs/challenge-scoring.md @@ -0,0 +1,46 @@ +# Challenge scoring + +Challenge scores are feedback, not a measure of someone’s potential as a Rust developer. They show whether the reasoning needed for a particular prompt is present and help a learner decide what to revisit next. + +## Shared rules + +Give credit for a correct conclusion and for the reasoning that supports it. A lucky answer without an explanation is weaker evidence than a well-reasoned answer with a small mistake. Do not deduct points for using different, idiomatic wording when the underlying Rust rule is correct. + +For any code-based challenge, judge the current toolchain behaviour described by the item or lab. If a diagnostic changes wording across Rust releases, score the learner’s explanation of the language rule rather than exact diagnostic text. + +## Short structured questions + +| Challenge type | Full-credit evidence | Score | +| --- | --- | --- | +| Multiple choice or design choice | Correct choice and a reason that identifies the relevant trade-off | 2 points | +| Will It Compile? | Correct prediction and the ownership, borrowing, type, trait, or lifetime rule that decides it | 2 points | +| Predict output | Correct output and an explanation of the evaluated expressions or control flow | 2 points | +| Fix error | A compiling, proportionate fix and an explanation of the original rule violation | 2 points | + +Award one point when the conclusion is correct but the explanation is missing or materially incomplete. Award zero when the conclusion is incorrect or based on a contradictory explanation. + +## Code-review challenges + +Score each review out of four points. Award one point each for identifying the main issue, explaining the concrete consequence, proposing a proportionate improvement, and naming a relevant trade-off or boundary. A review does not need to propose the same fix as the stored answer when its alternative is correct and fits the code’s constraints. + +## Compiler-error labs + +Score each lab out of four points. Award one point each for predicting that the code fails, naming the primary rule involved, describing why the code violates it, and producing or recognizing a sound fixed version. Error codes are useful reference points but are not required for full credit unless the prompt specifically asks for one. + +## Interview prompts + +Interview prompts are evaluated on reasoning, not memorized vocabulary. Use this four-point scale for each prompt. + +| Score | Evidence | +| --- | --- | +| 0 | The answer does not address the question or contains a fundamental misconception. | +| 1 | The answer identifies a relevant concept but cannot apply it to the situation. | +| 2 | The answer gives a correct baseline explanation and one relevant trade-off. | +| 3 | The answer explains a sound approach, trade-offs, and failure or edge cases. | +| 4 | The answer is technically precise, surfaces assumptions, compares viable alternatives, and justifies a decision for the stated context. | + +Use the question’s `evaluation_criteria` as the checklist for a score of 2 or higher. A senior-level prompt should reward clear assumptions, constraints, and trade-offs; it should not demand a single predetermined implementation. + +## Using results + +Treat a low score as a study signal, not a stop sign. Follow the question’s canonical reference, restate the rule in your own words, and retry a related challenge after making a small working example. Website progress features may present these scores later, but this repository does not collect or transmit learner results. diff --git a/docs/content-metadata.md b/docs/content-metadata.md new file mode 100644 index 0000000..2ca7bd7 --- /dev/null +++ b/docs/content-metadata.md @@ -0,0 +1,56 @@ +# Content metadata + +Topic metadata gives repository tools and the future website a shared description of each learning topic without copying lesson bodies. Version 1 uses JSON so editors, Rust tooling, CI, and Astro can consume the same source without a format conversion layer. + +The [topic authoring guide](authoring/topic-guide.md) explains when to create a topic, how to choose its boundary, and how metadata evidence relates to the learning material. The [content rubric](authoring/content-rubric.md) defines the human review that is required before a topic can become Stable. + +The formal contract is [topic-metadata-v1.schema.json](../schemas/topic-metadata-v1.schema.json). A complete Review-status example is available in [topic-metadata.json](examples/topic-metadata.json). Metadata migration is staged: migrate a canonical topic when its learner boundary and currently supported evidence can be described truthfully. + +## File placement + +Each migrated topic stores its metadata in `metadata.json` beside its learning material. The topic ID is independent of that directory path, so a later repository normalization can move a topic without changing prerequisite links, track membership, or website URLs. + +## Required fields + +- `schema_version` selects the contract version. Version 1 is the only accepted value. +- `id` is a unique lowercase kebab-case identifier that must remain stable when files move. +- `title` is the learner-facing topic name. +- `status` is one of `planned`, `draft`, `review`, `stable`, or `deprecated` and follows [CONTENT_STATUS.md](../CONTENT_STATUS.md). +- `level` is one of `beginner`, `intermediate`, `advanced`, or `expert`. +- `estimated_minutes` is a positive estimate for completing the topic. +- `prerequisites` contains stable topic IDs. The list may be empty, but a topic cannot require itself. During staged migration, an unpublished topic may reference an intended ID whose metadata has not yet been added; the validator reports that reference as a warning. A published topic must reference metadata that exists within the validated repository scope. +- `concepts` contains one or more lowercase kebab-case concept tags. +- `tracks` contains one or more of `core`, `java`, `python`, `cpp`, or `go`. +- `learning_objectives` contains one or more concrete outcomes stated from the learner's perspective. +- `website` controls publication and ordering without moving or duplicating the source material. +- `validation` records evidence for the content rubric, examples, and exercises as `pending`, `passed`, or `not_applicable`. + +The optional `$schema` property lets an editor associate a metadata file with the JSON Schema. It is an editing aid and is omitted from exported topic records. + +## Stability and publication rules + +A topic cannot use `stable` until its content rubric is `passed` and its example and exercise evidence is either `passed` or `not_applicable`. A topic cannot set `website.published` to `true` unless it is Stable, and every published topic requires a numeric website order. These rules are enforced by the Rust validator as well as represented in the JSON Schema. + +Passing metadata validation does not promote a topic. Status changes still require the evidence described in `CONTENT_STATUS.md` and the applicable criteria in the content rubric, and must be reviewed with the content change. The validator checks duplicate IDs across every parsed metadata file, even when one of those files has other semantic errors, so an invalid file cannot hide an identifier collision. + +## Validator and export commands + +Run the validator against one metadata file while authoring it: + +```bash +cargo run --manifest-path tools/contentctl/Cargo.toml -- validate docs/examples/topic-metadata.json +``` + +After topic metadata exists in the curriculum, validate a directory to find every nested `metadata.json` file: + +```bash +cargo run --manifest-path tools/contentctl/Cargo.toml -- validate . +``` + +The export command validates the same input, sorts topics by stable ID, records each source path, and writes deterministic JSON to standard output: + +```bash +cargo run --manifest-path tools/contentctl/Cargo.toml -- export . +``` + +The website will consume this export boundary in a later phase. Generated exports are build artifacts and should not replace canonical metadata or lesson files in this repository. diff --git a/docs/curriculum/common-mistakes.md b/docs/curriculum/common-mistakes.md new file mode 100644 index 0000000..4460623 --- /dev/null +++ b/docs/curriculum/common-mistakes.md @@ -0,0 +1,24 @@ +# Common Rust mistakes and how to recover + +Rust gives unusually direct feedback when a program's assumptions do not line up with its ownership, type, or error-handling rules. Treat that feedback as a clue about the model, not as an obstacle to work around. This reference names mistakes that commonly slow down new learners and points to the lesson that helps correct each one. + +| Mistake | What to do instead | Canonical lesson | +| --- | --- | --- | +| Expecting every assignment to make an independent copy | Check whether the value implements `Copy`; move an owned value only when the new binding should take responsibility for it, or borrow it when both places only need access. | [Ownership](../../01-core-fundamentals/ownership/README.md) | +| Adding `.clone()` before understanding the move error | First decide who should own the value and how long each use needs it. Clone only when two independent owned values are genuinely required. | [Ownership](../../01-core-fundamentals/ownership/README.md) | +| Trying to keep a mutable reference while another reference is still in use | Keep the read-only or mutable access in the smallest useful scope, then make the next borrow after the earlier one has ended. | [Ownership](../../01-core-fundamentals/ownership/README.md) | +| Treating `let` bindings as mutable by default | Mark a binding `mut` only when the binding's value must change; use shadowing when a transformed value deserves a new binding. | [Variables and mutability](../../01-core-fundamentals/variables_and_mutability/README.md) | +| Reaching for `unwrap()` in code that can receive ordinary bad input | Model absence with `Option` and recoverable failure with `Result`; use `?`, matching, or a deliberate fallback to make the chosen behaviour clear. | [Error handling basics](../../02-standard-library/error_handling_basics/README.md) | +| Using indexing when an input can be out of range | Prefer methods such as `get` when missing data is an expected possibility, then handle the returned `Option`. | [Collections](../../02-standard-library/collections/README.md) | +| Writing loops that collect temporary values when an iterator expresses the work directly | Start with `iter`, `iter_mut`, or `into_iter`, then use adapters such as `map`, `filter`, and `collect` when they make the transformation clearer. | [Iterator patterns](../../02-standard-library/iterator_patterns/README.md) | +| Assuming an `if` block or `match` arm can quietly return a value of a different type | Read the type mismatch from the inside out, make every branch agree on an output type, and introduce an enum when the alternatives are meaningfully different. | [Control flow](../../01-core-fundamentals/control_flow/README.md) | +| Editing until an error disappears without reading the diagnostics | Read the primary error, its highlighted span, and any suggested fix. Reduce the example if needed, then make one intentional change and compile again. | [Debugging](../../03-tooling-and-quality/debugging/README.md) | +| Leaving warnings and formatting until the end of a change | Run `cargo fmt`, `cargo clippy`, and `cargo check` in the normal edit loop so small problems stay small. | [Code quality tools](../../03-tooling-and-quality/code_quality_tools/README.md) | + +## A useful recovery loop + +When a Rust error feels opaque, pause before changing the code. State what you expected to happen, identify which value or type the compiler is discussing, and compare that expectation with the relevant rule. Try the smallest change that tests your explanation. The [compiler-error labs](../../labs/compiler-errors/) are a good place to practise this loop without risking a larger program. + +## When to ask for help + +Bring a reduced example, the full diagnostic, and a short description of the behaviour you wanted. That gives another learner or reviewer enough context to explain the rule rather than merely suggesting a patch. If you are still early in the curriculum, return to the matching stage in the [From Zero path](from-zero.md) before adding more abstractions. diff --git a/docs/curriculum/from-zero.md b/docs/curriculum/from-zero.md new file mode 100644 index 0000000..8ac6b42 --- /dev/null +++ b/docs/curriculum/from-zero.md @@ -0,0 +1,23 @@ +# From Zero: the canonical Rust path + +This is the recommended route for someone starting Rust without assuming prior systems-programming experience. Work through a stage in order, run the examples, and use the checkpoint before moving on. Modules marked Review contain useful material and automated checks, but they are not yet represented as Stable website content. + +| Stage | Learn | Start here | Checkpoint | +| --- | --- | --- | --- | +| 1. Setup and syntax | Toolchain, bindings, types, control flow | [Module 00](../../00-setup-and-basics/) | Run one Cargo example and explain the difference between a binding and a value. | +| 2. Ownership | Moves, borrowing, slices, lifetimes | [Module 01](../../01-core-fundamentals/) | Explain why a `String` move differs from an integer assignment and repair a borrowing error. | +| 3. Standard library | Collections, strings, iterators, errors | [Module 02](../../02-standard-library/) | Choose `Option` or `Result` for a realistic boundary and justify it. | +| 4. Everyday workflow | Cargo, tests, formatting, Clippy, documentation | [Module 03](../../03-tooling-and-quality/) | Add a test, run `cargo fmt`, and resolve a useful lint. | +| 5. Small programs | Input, state, files, command-line programs | [Module 04](../../04-simple-programs/) | Finish a program without copying its solution first. | +| 6. Applied practice | Games, randomness, state transitions | [Module 05](../../05-cli-and-console-games/) | Trace a state change and add an edge-case test. | +| 7. Type-system depth | Enums, traits, generics, lifetimes | [Module 06](../../06-intermediate-rust/) | Design a small trait-based API and explain its ownership choices. | + +## How to study a topic + +Read the topic overview, run the smallest example, predict one change, and let the compiler confirm or challenge that prediction. Then attempt the exercise or a small variation before reading solution notes. If a compiler error is unfamiliar, use the [compiler-error lab](../../labs/compiler-errors/) after first trying to explain the failure yourself. + +## What comes later + +Modules 07 through 10 are valuable reference and project material, but they are not a required first pass through Rust. Return to them after the seven stages above, choosing material that supports the program you want to build. Use the language-transition tracks alongside this path, not instead of it. + +Use the [core concept prerequisites](prerequisites.md) when you need to understand why a later topic depends on an earlier one. diff --git a/docs/curriculum/prerequisites.md b/docs/curriculum/prerequisites.md new file mode 100644 index 0000000..254749b --- /dev/null +++ b/docs/curriculum/prerequisites.md @@ -0,0 +1,41 @@ +# Core concept prerequisites + +This map gives the recommended dependency order for the canonical From-Zero route. It is a learning aid, not a claim that every listed topic already has migrated metadata or Stable status. The topic metadata validator remains the source of truth for migrated prerequisite IDs. + +```text +installation + └── variables-and-mutability + ├── data-types + ├── control-flow + └── functions + └── ownership + ├── borrowing + │ └── lifetimes + ├── strings-and-collections + └── error-handling + ├── option + └── result + ├── enums-and-pattern-matching + ├── traits + │ └── generics + └── iterator-patterns + └── testing-and-tooling +``` + +## How to use the map + +Follow an edge when a topic’s examples assume the earlier idea. For example, start ownership before borrowing, and understand `Option` and `Result` before trying to design an error-handling API. You can revisit a branch without restarting the whole route; the graph is about dependencies, not a measure of difficulty. + +## Canonical lessons + +| Concept | Canonical lesson | +| --- | --- | +| Variables and mutability | [Module 00 variables](../../00-setup-and-basics/variables_and_mutability/) and [Module 01 topic](../../01-core-fundamentals/variables_and_mutability/) | +| Data types and control flow | [Data types](../../01-core-fundamentals/data_types/) and [control flow](../../01-core-fundamentals/control_flow/) | +| Functions and ownership | [Functions](../../01-core-fundamentals/functions/) and [ownership](../../01-core-fundamentals/ownership/) | +| Borrowing and lifetimes | [Borrowing](../../01-core-fundamentals/borrowing/) and [lifetimes](../../01-core-fundamentals/lifetimes/) | +| Errors and standard-library patterns | [Error handling](../../01-core-fundamentals/error_handling/), [Option and Result](../../02-standard-library/error_handling_basics/), and [iterators](../../02-standard-library/iterator_patterns/) | +| Traits and generics | [Traits](../../06-intermediate-rust/traits_and_polymorphism/) and [generics](../../06-intermediate-rust/generics/) | +| Testing and tooling | [Module 03](../../03-tooling-and-quality/) | + +As more topics migrate to metadata, their stable IDs and validated prerequisite edges should be added to this map. Do not infer a topic is Stable merely because it appears in the graph. diff --git a/docs/curriculum/study-time.md b/docs/curriculum/study-time.md new file mode 100644 index 0000000..1c13035 --- /dev/null +++ b/docs/curriculum/study-time.md @@ -0,0 +1,27 @@ +# Study time for the From-Zero Rust path + +These estimates describe focused learning time: reading, running examples, changing code, and completing the checkpoint for each stage. They are planning ranges rather than promises. Rust experience varies widely because the compiler asks learners to make ownership and type decisions that may be new even when the syntax is familiar. + +The route below follows the [canonical From-Zero path](from-zero.md). It is deliberately a first pass: the aim is a working mental model and small-program confidence, not mastery of every linked module. + +| Stage | Canonical module | Suggested focused time | What affects the estimate | +| --- | --- | --- | --- | +| 1. Setup and syntax | [Module 00: Setup and basics](../../00-setup-and-basics/) | 4–8 hours | Toolchain setup can be quick, while a first programming language often needs more time for expressions, types, and control flow. | +| 2. Ownership | [Module 01: Core fundamentals](../../01-core-fundamentals/) | 10–18 hours | Learners new to ownership, borrowing, slices, or lifetimes should expect to spend time making and repairing small compiler mistakes. | +| 3. Standard library | [Module 02: Standard library](../../02-standard-library/) | 8–14 hours | Time grows when collections, iterator adapters, string handling, and error design are all new. | +| 4. Everyday workflow | [Module 03: Tooling and quality](../../03-tooling-and-quality/) | 4–7 hours | The lower end suits someone comfortable with command-line development and tests; the upper end includes writing and debugging a few tests. | +| 5. Small programs | [Module 04: Simple programs](../../04-simple-programs/) | 8–16 hours | Building a program independently, including file or command-line behaviour, takes longer than following an example. | +| 6. Applied practice | [Module 05: CLI and console games](../../05-cli-and-console-games/) | 6–12 hours | Extra time is useful for tracing state changes, testing edge cases, and adding a small feature of your own. | +| 7. Type-system depth | [Module 06: Intermediate Rust](../../06-intermediate-rust/) | 12–20 hours | Traits, generics, and lifetimes repay deliberate practice; experienced developers may move faster through syntax but still need time for Rust's semantics. | + +## Planning a first pass + +Most learners should budget roughly 52–95 focused hours for the seven stages. At five focused hours each week, that is about 10–19 weeks; at ten focused hours each week, it is about 5–10 weeks. The ranges include practice and troubleshooting, but not long detours into a personal project. + +Treat a stage checkpoint as the signal to move forward. If the checkpoint still feels difficult, repeat a small example or exercise rather than trying to cover more topics in the same session. Short, regular sessions tend to make compiler feedback easier to absorb than occasional marathon sessions. + +## Adjusting the estimate + +Add time if Rust is your first programming language, if you are learning command-line tooling at the same time, or if you want to write every exercise from scratch before seeing hints. You may need less time in the setup and workflow stages if you already use Cargo-like tooling, but do not skip ownership practice because you know another language. + +The later modules are optional for the first route. When you are ready for a specific goal, use [advanced concepts](../../07-advanced-concepts/), [design patterns](../../08-design-patterns/), [interview challenges](../../challenges/interview/), or [real-world Rust](../../10-real-world-rust/) as targeted follow-up rather than extending this estimate into an open-ended total. diff --git a/docs/examples/topic-metadata.json b/docs/examples/topic-metadata.json new file mode 100644 index 0000000..1fba40c --- /dev/null +++ b/docs/examples/topic-metadata.json @@ -0,0 +1,27 @@ +{ + "$schema": "../../schemas/topic-metadata-v1.schema.json", + "schema_version": 1, + "id": "ownership-borrowing", + "title": "Ownership and Borrowing", + "status": "review", + "level": "beginner", + "estimated_minutes": 90, + "prerequisites": ["variables", "functions"], + "concepts": ["ownership", "move-semantics", "borrowing", "mutable-borrowing"], + "tracks": ["core", "java", "python", "cpp", "go"], + "learning_objectives": [ + "Explain why Rust uses ownership.", + "Predict when a value is moved.", + "Distinguish immutable and mutable borrowing.", + "Fix common borrow checker errors." + ], + "website": { + "published": false, + "order": null + }, + "validation": { + "content_rubric": "pending", + "examples": "passed", + "exercises": "passed" + } +} diff --git a/docs/indexes/README.md b/docs/indexes/README.md new file mode 100644 index 0000000..bcae2a8 --- /dev/null +++ b/docs/indexes/README.md @@ -0,0 +1,13 @@ +# Concept indexes + +These indexes are a way to find the primary lesson for an idea without replacing the recommended learning path. Start with [From Zero: the canonical Rust path](../curriculum/from-zero.md) if you are new to Rust, then use an index when you need to revisit a concept or connect it to the next one. + +Each link points to the repository's main lesson for that subject. Some concepts appear in more than one place because Rust ideas reinforce one another; the index identifies the best first stop and names useful follow-up lessons where that helps. + +## Choose an index + +- [Foundations](foundations.md) covers syntax, values, control flow, ownership, and the standard library essentials needed to read and write small Rust programs. +- [Types and program design](types-and-design.md) covers traits, generics, enums, pattern matching, lifetimes, and the choices that shape program interfaces. +- [Building and maintaining programs](building-programs.md) covers testing, debugging, documentation, command-line programs, files, and introductory concurrency. + +These pages do not set a content status. Check [Content status](../../CONTENT_STATUS.md) when you need to know whether an area is Planned, Draft, Review, or Stable. diff --git a/docs/indexes/building-programs.md b/docs/indexes/building-programs.md new file mode 100644 index 0000000..3403498 --- /dev/null +++ b/docs/indexes/building-programs.md @@ -0,0 +1,19 @@ +# Building and maintaining programs concept index + +This index connects language knowledge to the routine work of building a useful program. Follow the module sequence for a full learning experience; use these links when a project exposes a gap in your testing, diagnostics, I/O, or concurrency knowledge. + +| Task or concept | Start here | Useful next step | +| --- | --- | --- | +| Run checks, format code, and understand the development toolchain | [Tooling and quality](../../03-tooling-and-quality/README.md) | [Testing](../../03-tooling-and-quality/testing/README.md) | +| Write and run unit, integration, or documentation tests | [Testing](../../03-tooling-and-quality/testing/README.md) | [Documentation](../../03-tooling-and-quality/documentation/README.md) | +| Investigate a failing program and use compiler feedback | [Debugging](../../03-tooling-and-quality/debugging/README.md) | [Compiler-error labs](../../labs/compiler-errors/README.md) | +| Explain a public API or maintain project documentation | [Documentation](../../03-tooling-and-quality/documentation/README.md) | [Project organization](../../10-real-world-rust/project_organization/README.md) | +| Read command-line arguments and build a small CLI | [CLI arguments](../../04-simple-programs/cli_arguments/README.md) | [Todo CLI project](../../09-mini-projects/todo_cli/README.md) | +| Read, write, and transform files | [File I/O basics](../../04-simple-programs/file_io_basics/README.md) | [Text processing](../../04-simple-programs/text_processing/README.md) | +| Organize code as an application with multiple responsibilities | [Mini projects](../../09-mini-projects/README.md) | [Project organization](../../10-real-world-rust/project_organization/README.md) | +| Coordinate work across threads and understand shared-state constraints | [Concurrency introduction](../../10-real-world-rust/concurrency_intro/README.md) | [Advanced async](../../07-advanced-concepts/advanced_async/README.md) | +| Practice explaining a design or reviewing a small change | [Code-review challenges](../../challenges/code-review/README.md) | [Interview challenges](../../challenges/interview/README.md) | + +## Use the compiler as part of the workflow + +Run a small check after each focused change, not only at the end of a project. When an error is unfamiliar, reduce the program to the smallest example that still fails, predict what ownership or type rule applies, and then consult the linked lesson. The compiler-error labs are deliberately broken examples designed for that kind of practice. diff --git a/docs/indexes/foundations.md b/docs/indexes/foundations.md new file mode 100644 index 0000000..34989ff --- /dev/null +++ b/docs/indexes/foundations.md @@ -0,0 +1,22 @@ +# Foundations concept index + +Use this index after the setup module to find the first lesson for a core language idea. The sequence generally follows the [canonical path](../curriculum/from-zero.md), but you can return here when a compiler message or an exercise points to a concept you want to refresh. + +| Concept | Start here | Useful next step | +| --- | --- | --- | +| Installing Rust, Cargo, and the command line | [Setup and basics](../../00-setup-and-basics/README.md) | [Tooling and quality](../../03-tooling-and-quality/README.md) | +| Variables, `mut`, constants, and shadowing | [Variables and mutability](../../01-core-fundamentals/variables_and_mutability/README.md) | [Data types](../../01-core-fundamentals/data_types/README.md) | +| Scalars, tuples, arrays, and type inference | [Data types](../../01-core-fundamentals/data_types/README.md) | [Functions](../../01-core-fundamentals/functions/README.md) | +| Functions, parameters, return values, and expressions | [Functions](../../01-core-fundamentals/functions/README.md) | [Control flow](../../01-core-fundamentals/control_flow/README.md) | +| `if`, `match`, loops, and exhaustive decisions | [Control flow](../../01-core-fundamentals/control_flow/README.md) | [Enums and pattern matching](../../06-intermediate-rust/enums_and_pattern_matching/README.md) | +| Ownership, moves, and when values are dropped | [Ownership](../../01-core-fundamentals/ownership/README.md) | [Ownership and borrowing](../../06-intermediate-rust/ownership_and_borrowing/README.md) | +| Shared and mutable references | [Ownership and borrowing](../../06-intermediate-rust/ownership_and_borrowing/README.md) | [Lifetimes](../../06-intermediate-rust/lifetimes/README.md) | +| `String`, `&str`, parsing, and text operations | [String operations](../../02-standard-library/string_operations/README.md) | [Collections](../../02-standard-library/collections/README.md) | +| `Vec`, maps, sets, and choosing a collection | [Collections](../../02-standard-library/collections/README.md) | [Iterator patterns](../../02-standard-library/iterator_patterns/README.md) | +| `iter`, `map`, `filter`, `fold`, and `collect` | [Iterator patterns](../../02-standard-library/iterator_patterns/README.md) | [Common traits](../../02-standard-library/common_traits/README.md) | +| `Copy`, `Clone`, `Debug`, `Display`, and conversions | [Common traits](../../02-standard-library/common_traits/README.md) | [Traits and polymorphism](../../06-intermediate-rust/traits_and_polymorphism/README.md) | +| Absence with `Option` and recoverable failure with `Result` | [Error handling basics](../../02-standard-library/error_handling_basics/README.md) | [Advanced error handling](../../10-real-world-rust/error_handling_advanced/README.md) | + +## A practical order for a stuck learner + +If a program fails because a value was moved or borrowed, revisit ownership before looking for a library workaround. If a `match` feels unwieldy, review enums and pattern matching. If iterator code is difficult to read, first make the equivalent loop work, then return to iterator patterns and change one operation at a time. diff --git a/docs/indexes/types-and-design.md b/docs/indexes/types-and-design.md new file mode 100644 index 0000000..9331937 --- /dev/null +++ b/docs/indexes/types-and-design.md @@ -0,0 +1,19 @@ +# Types and program design concept index + +Rust's type-system features are most useful when they solve a concrete design problem. Use this index to locate the primary lesson for the question you are trying to answer, rather than treating traits, generics, enums, and lifetimes as interchangeable tools. + +| Design question or concept | Start here | Useful next step | +| --- | --- | --- | +| How do I describe a value that can be one of several meaningful cases? | [Enums and pattern matching](../../06-intermediate-rust/enums_and_pattern_matching/README.md) | [Error handling basics](../../02-standard-library/error_handling_basics/README.md) | +| How do I make a decision for every possible case? | [Control flow](../../01-core-fundamentals/control_flow/README.md) | [Enums and pattern matching](../../06-intermediate-rust/enums_and_pattern_matching/README.md) | +| How do I share behavior without a class hierarchy? | [Traits and polymorphism](../../06-intermediate-rust/traits_and_polymorphism/README.md) | [Common traits](../../02-standard-library/common_traits/README.md) | +| How do I write one function or type that works with several types? | [Generics](../../06-intermediate-rust/generics/README.md) | [Traits and polymorphism](../../06-intermediate-rust/traits_and_polymorphism/README.md) | +| Which trait bounds belong in a public function signature? | [Traits and polymorphism](../../06-intermediate-rust/traits_and_polymorphism/README.md) | [Generics](../../06-intermediate-rust/generics/README.md) | +| Why can a reference not outlive the value it points to? | [Lifetimes](../../06-intermediate-rust/lifetimes/README.md) | [Ownership and borrowing](../../06-intermediate-rust/ownership_and_borrowing/README.md) | +| Should this function own its input or borrow it? | [Ownership and borrowing](../../06-intermediate-rust/ownership_and_borrowing/README.md) | [Ownership](../../01-core-fundamentals/ownership/README.md) | +| How should a type report an expected absence or failure? | [Error handling basics](../../02-standard-library/error_handling_basics/README.md) | [Enums and pattern matching](../../06-intermediate-rust/enums_and_pattern_matching/README.md) | +| How do I make values easy to inspect, print, clone, or parse? | [Common traits](../../02-standard-library/common_traits/README.md) | [Traits and polymorphism](../../06-intermediate-rust/traits_and_polymorphism/README.md) | + +## Keep the distinctions sharp + +Enums model a known set of alternatives, while traits describe shared behavior. Generics let an API work with a family of types, while trait bounds state the capabilities that family must provide. Lifetimes do not extend a value's life; they describe relationships the compiler must be able to prove. Beginning with the lesson that matches the design question makes those distinctions easier to retain. diff --git a/docs/production/project-architecture-and-observability.md b/docs/production/project-architecture-and-observability.md new file mode 100644 index 0000000..a313230 --- /dev/null +++ b/docs/production/project-architecture-and-observability.md @@ -0,0 +1,37 @@ +# Project Architecture and Observability + +The advanced examples are deliberately small, but their boundaries are the same boundaries a production Rust service needs. Use the Axum example in [modern web APIs](../../07-advanced-concepts/modern_web_apis/02-axum-api/README.md) as the concrete reference: routes compose handlers, `AppState` owns the database pool, middleware surrounds the router, and handlers convert infrastructure failures into HTTP responses. + +## Keep dependency direction simple + +Start at the edge and move inward: transport code parses HTTP or messages, application code coordinates a use case, domain code owns business rules, and infrastructure code implements databases or external clients. A handler should be thin enough to test its decision separately from Axum. State should contain long-lived, shareable dependencies such as a connection pool or client, not request-local data. + +The repository's Axum example currently keeps this structure in one file so the framework concepts stay visible. When it grows, split by responsibility rather than by technical novelty: `routes` wires endpoints, `handlers` performs transport translation, `service` coordinates operations, `model` owns values, and `infrastructure` creates clients and pools. Keep the router composition point obvious; it is where middleware and state ownership can be reviewed together. + +## Observability is part of the boundary + +`TraceLayer::new_for_http()` in the Axum example creates request spans, while `tracing_subscriber::fmt::init()` installs a local formatter. That is enough to see request activity during development, but logs only become operationally useful when they answer which request failed, which dependency was involved, and how long the operation took. + +Add fields that describe the operation rather than sensitive payloads. Good fields include route name, HTTP method, response status, elapsed time, retry count, and a stable request or correlation identifier. Do not record authorization headers, access tokens, passwords, full database URLs, or personal data. Emit a structured error at the point where context is richest, then translate it to the client-facing error once. + +```rust +tracing::info!(user_id = id, "creating user record"); +tracing::warn!(%request_id, status = 503, "database temporarily unavailable"); +``` + +The example does not yet create request identifiers or metrics. Treat those as the next production increment, not as behavior it already guarantees. + +## Health is not readiness + +The sample `/api/health` route proves that the process can answer HTTP. A production service normally needs a separate readiness check that verifies only dependencies required to receive traffic, such as a database pool. Keep this check cheap and bounded by a timeout. Liveness should not restart a process merely because a downstream dependency is temporarily unavailable; readiness should remove it from traffic while the dependency is unavailable. + +## Practical delivery checklist + +- Define a route-level request span and propagate a request identifier through outbound calls. +- Configure log level and output format through environment or deployment configuration, not source edits. +- Add bounded timeouts, retries only where the operation is safe to repeat, and metrics for latency, errors, and saturation. +- Keep database, queue, and HTTP client construction at the composition root so tests can substitute them. +- Give health, readiness, and dependency failures distinct semantics. +- Exercise error paths and verify that logs preserve useful context without leaking secrets. + +This guidance describes an architecture direction for the existing examples. It is not a claim that the sample API includes authentication, metrics export, distributed tracing, or a production deployment configuration. diff --git a/docs/production/unsafe-safety-contracts.md b/docs/production/unsafe-safety-contracts.md new file mode 100644 index 0000000..29c0b49 --- /dev/null +++ b/docs/production/unsafe-safety-contracts.md @@ -0,0 +1,27 @@ +# Unsafe Safety Contracts + +`unsafe` is a promise made by the author, not a performance switch. Safe callers rely on the code at an unsafe boundary to preserve Rust's aliasing, lifetime, initialization, and thread-safety rules. Put the smallest possible unsafe operation behind a safe API whenever that API can enforce the preconditions. + +## A contract before an unsafe block + +Write down the contract immediately above the block or unsafe function. It should identify the invariants, who establishes them, how they are checked, and what could make the operation unsound. A useful contract is concrete: “the pointer was produced by this allocation, is aligned for `T`, names `len` initialized elements, and no mutable alias exists for the returned slice.” “Caller must be careful” is not a contract. + +Use a safe abstraction when the standard library already provides one. `OnceLock` replaces most hand-written `static mut` initialization. `Mutex`, atomics, channels, and scoped threads cover common shared-state patterns without a custom safety proof. FFI belongs in a narrow wrapper that owns conversion, null checks, error translation, and resource cleanup. + +## Review checklist + +- State every precondition and whether the caller or wrapper verifies it. +- Keep raw pointers, `static mut`, inline assembly, and FFI calls out of ordinary business logic. +- Explain ownership across each FFI boundary, including which side frees each allocation. +- Validate nullability, lengths, alignment, UTF-8 or encoding assumptions, and integer conversions before dereferencing or constructing references. +- Document thread-affinity, reentrancy, and callback lifetime rules for foreign libraries. +- Test the safe wrapper’s error paths; use Miri or sanitizers when the project and platform support them. +- Prefer an `unsafe fn` only when its caller genuinely must uphold a precondition. Otherwise expose a safe function and contain the block inside it. + +## Architecture boundary + +This repository’s runnable advanced examples do not require FFI or raw-pointer implementations. The SIMD snippets in [performance optimization](../../07-advanced-concepts/performance_optimization/README.md) are illustrative platform-specific sketches, not complete implementations or a recommendation to bypass portable code. Any future runnable SIMD or FFI example must include its contract beside the unsafe operation, a portable fallback, target detection where applicable, and a command that checks the safe path. + +## Singleton initialization + +Do not use `static mut` plus `Once` for an ordinary singleton. The singleton guide now uses `OnceLock`, whose API expresses one-time initialization without exposing mutable global state. This removes an unnecessary unsafe boundary rather than trying to document around it. diff --git a/docs/quiz-content.md b/docs/quiz-content.md new file mode 100644 index 0000000..1aec41d --- /dev/null +++ b/docs/quiz-content.md @@ -0,0 +1,33 @@ +# Quiz content + +Quiz items are small reasoning exercises, not trivia cards. They live in `challenges/quiz-items/` as one JSON object per file and follow [quiz-item-v1.schema.json](../schemas/quiz-item-v1.schema.json). + +Use `cargo run --manifest-path tools/contentctl/Cargo.toml -- validate-quiz challenges/quiz-items` to validate every item. The validator checks the JSON shape, stable IDs, duplicate IDs, required explanations and references, and the answer format required by each question type. + +## Item contract + +Every item has a stable `id`, a canonical-topic `topic`, a difficulty, concept tags, the learner-facing question, a correct answer, an explanation, and at least one repository reference. `code` is required for `will_it_compile`, `predict_output`, `code_review`, and `fix_error` questions. Multiple-choice and design-choice questions need at least two choices, and their answer must name one of those choices. + +The six supported question types are `multiple_choice`, `will_it_compile`, `predict_output`, `code_review`, `fix_error`, and `design_choice`. A question should reveal a useful misconception or decision point, then explain the reasoning in language a learner can act on. + +## Will It Compile? + +Use `will_it_compile` when the central learning goal is a compiler decision, not program output or a design preference. Supply a minimal code sample, set `answer.kind` to `compiles`, and set `answer.value` to the string `true` or `false`. Verify the result with the current Rust toolchain where practical, then explain the language rule behind it rather than merely repeating the diagnostic. + +Use the shared [challenge scoring rules](challenge-scoring.md) when reviewing reasoning-based answers. The score recognises both a correct conclusion and the rule that supports it. + +## Authoring guidance + +Keep the prompt self-contained. Show only the code needed to reason about the question, avoid unstated assumptions, and use a reference that lets the learner continue studying the concept. Do not publish a question merely because its JSON validates: the explanation must accurately describe Rust’s behaviour. + +For code that is intended to compile or fail, verify the claim with the Rust toolchain whenever practical. The 50-item foundation set contains both compile-behaviour questions and conceptual questions; it does not make claims about a remote runner or a public quiz interface. + +## Foundation set + +The first 50 items are deliberately balanced across the skills a new Rust learner needs to practice. + +- 10 syntax and core-language questions +- 15 ownership and borrowing questions +- 10 types and traits questions +- 10 error-handling and collections questions +- 5 Cargo and tooling questions diff --git a/labs/compiler-errors/Makefile b/labs/compiler-errors/Makefile new file mode 100644 index 0000000..c4e53e2 --- /dev/null +++ b/labs/compiler-errors/Makefile @@ -0,0 +1,28 @@ +RUSTC ?= rustc +LABS := moved-value multiple-mutable-borrows lifetime-too-short trait-bound-not-satisfied send-sync + +.PHONY: check + +check: + @for lab in $(LABS); do \ + expected=$$(cat $$lab/expected-error.txt); \ + output=$$(mktemp); \ + if $(RUSTC) --edition=2021 --crate-type lib $$lab/broken.rs --emit=metadata -o $$output.rmeta >$$output 2>&1; then \ + echo "$$lab: broken.rs unexpectedly compiled"; \ + rm -f $$output $$output.rmeta; \ + exit 1; \ + fi; \ + if ! grep -q "$$expected" $$output; then \ + echo "$$lab: expected compiler error $$expected"; \ + cat $$output; \ + rm -f $$output $$output.rmeta; \ + exit 1; \ + fi; \ + if ! $(RUSTC) --edition=2021 --crate-type lib $$lab/fixed.rs --emit=metadata -o $$output.rmeta; then \ + echo "$$lab: fixed.rs did not compile"; \ + rm -f $$output $$output.rmeta; \ + exit 1; \ + fi; \ + rm -f $$output $$output.rmeta; \ + echo "$$lab: ok"; \ + done diff --git a/labs/compiler-errors/README.md b/labs/compiler-errors/README.md new file mode 100644 index 0000000..de52da6 --- /dev/null +++ b/labs/compiler-errors/README.md @@ -0,0 +1,7 @@ +# Compiler error lab + +Each lab contains deliberately broken Rust, a small fixed version, and a learner guide. Read `broken.rs`, predict the primary compiler error and its cause, then compare your reasoning with the guide before opening `fixed.rs`. + +Run `make check` in this directory to verify that every broken example fails with its recorded Rust error code and every fixed example type-checks. The check uses the local compiler, so diagnostics remain tied to the Rust version used to run it; the lesson explanations describe language rules rather than relying on diagnostic wording. + +The initial labs cover a moved value, overlapping mutable borrows, a returned reference to a local value, an unsatisfied trait bound, and sending a non-thread-safe type across a thread boundary. diff --git a/labs/compiler-errors/lifetime-too-short/README.md b/labs/compiler-errors/lifetime-too-short/README.md new file mode 100644 index 0000000..36b1578 --- /dev/null +++ b/labs/compiler-errors/lifetime-too-short/README.md @@ -0,0 +1,9 @@ +# Reference to a local value + +The function wants to return a greeting by reference. Predict why `broken.rs` fails before compiling it. + +Hint: the returned reference must remain valid after the function has returned. + +`message` is dropped when `greeting` ends, so a reference to it cannot safely escape. The compiler reports E0515. `fixed.rs` returns a string literal, whose `static` lifetime is sufficient for the returned reference. + +An alternative is to return an owned `String` when the greeting must be constructed during the function call. Do not add a lifetime annotation to a reference unless the referenced data actually lives long enough. diff --git a/labs/compiler-errors/lifetime-too-short/broken.rs b/labs/compiler-errors/lifetime-too-short/broken.rs new file mode 100644 index 0000000..e251b33 --- /dev/null +++ b/labs/compiler-errors/lifetime-too-short/broken.rs @@ -0,0 +1,4 @@ +pub fn greeting<'a>() -> &'a str { + let message = String::from("hello"); + &message +} diff --git a/labs/compiler-errors/lifetime-too-short/expected-error.txt b/labs/compiler-errors/lifetime-too-short/expected-error.txt new file mode 100644 index 0000000..c6cf15e --- /dev/null +++ b/labs/compiler-errors/lifetime-too-short/expected-error.txt @@ -0,0 +1 @@ +E0515 diff --git a/labs/compiler-errors/lifetime-too-short/fixed.rs b/labs/compiler-errors/lifetime-too-short/fixed.rs new file mode 100644 index 0000000..f238b08 --- /dev/null +++ b/labs/compiler-errors/lifetime-too-short/fixed.rs @@ -0,0 +1,3 @@ +pub fn greeting() -> &'static str { + "hello" +} diff --git a/labs/compiler-errors/moved-value/README.md b/labs/compiler-errors/moved-value/README.md new file mode 100644 index 0000000..41958d8 --- /dev/null +++ b/labs/compiler-errors/moved-value/README.md @@ -0,0 +1,9 @@ +# Moved value + +The program wants to retain a message and also create a second owned value with the same text. Predict why `broken.rs` fails before compiling it. + +Hint: assigning a `String` does not copy its heap allocation by default. + +`broken.rs` moves ownership from `message` to `stored`, then tries to use the moved binding. The compiler reports E0382. `fixed.rs` uses `clone` to make a deliberate second owned string, so both values can be read afterward. + +An alternative is to borrow the string when a second owner is unnecessary. Choose borrowing over cloning when the other code only needs temporary read access. diff --git a/labs/compiler-errors/moved-value/broken.rs b/labs/compiler-errors/moved-value/broken.rs new file mode 100644 index 0000000..fe06ca5 --- /dev/null +++ b/labs/compiler-errors/moved-value/broken.rs @@ -0,0 +1,5 @@ +pub fn reuse_after_move() { + let message = String::from("hello"); + let stored = message; + println!("{message} {stored}"); +} diff --git a/labs/compiler-errors/moved-value/expected-error.txt b/labs/compiler-errors/moved-value/expected-error.txt new file mode 100644 index 0000000..553a242 --- /dev/null +++ b/labs/compiler-errors/moved-value/expected-error.txt @@ -0,0 +1 @@ +E0382 diff --git a/labs/compiler-errors/moved-value/fixed.rs b/labs/compiler-errors/moved-value/fixed.rs new file mode 100644 index 0000000..3d39982 --- /dev/null +++ b/labs/compiler-errors/moved-value/fixed.rs @@ -0,0 +1,5 @@ +pub fn reuse_after_move() { + let message = String::from("hello"); + let stored = message.clone(); + println!("{message} {stored}"); +} diff --git a/labs/compiler-errors/multiple-mutable-borrows/README.md b/labs/compiler-errors/multiple-mutable-borrows/README.md new file mode 100644 index 0000000..605db60 --- /dev/null +++ b/labs/compiler-errors/multiple-mutable-borrows/README.md @@ -0,0 +1,9 @@ +# Multiple mutable borrows + +The function wants to append two values to one vector. Predict why `broken.rs` fails before compiling it. + +Hint: Rust allows one mutable reference or many immutable references to a value at one time. + +`broken.rs` creates `second` while `first` is still used later, so the two mutable borrows overlap. The compiler reports E0499. `fixed.rs` limits the first borrow to an inner scope before it creates the second borrow. + +An alternative is to use one mutable reference for both pushes. The important part is not the braces themselves; it is that the first exclusive borrow is no longer active. diff --git a/labs/compiler-errors/multiple-mutable-borrows/broken.rs b/labs/compiler-errors/multiple-mutable-borrows/broken.rs new file mode 100644 index 0000000..9735d01 --- /dev/null +++ b/labs/compiler-errors/multiple-mutable-borrows/broken.rs @@ -0,0 +1,7 @@ +pub fn append_twice() { + let mut values = vec![1]; + let first = &mut values; + let second = &mut values; + first.push(2); + second.push(3); +} diff --git a/labs/compiler-errors/multiple-mutable-borrows/expected-error.txt b/labs/compiler-errors/multiple-mutable-borrows/expected-error.txt new file mode 100644 index 0000000..1ae2407 --- /dev/null +++ b/labs/compiler-errors/multiple-mutable-borrows/expected-error.txt @@ -0,0 +1 @@ +E0499 diff --git a/labs/compiler-errors/multiple-mutable-borrows/fixed.rs b/labs/compiler-errors/multiple-mutable-borrows/fixed.rs new file mode 100644 index 0000000..b29842b --- /dev/null +++ b/labs/compiler-errors/multiple-mutable-borrows/fixed.rs @@ -0,0 +1,9 @@ +pub fn append_twice() { + let mut values = vec![1]; + { + let first = &mut values; + first.push(2); + } + let second = &mut values; + second.push(3); +} diff --git a/labs/compiler-errors/send-sync/README.md b/labs/compiler-errors/send-sync/README.md new file mode 100644 index 0000000..cfb5a57 --- /dev/null +++ b/labs/compiler-errors/send-sync/README.md @@ -0,0 +1,9 @@ +# Send and thread boundaries + +The function wants to move shared ownership of a number into a new thread. Predict why `broken.rs` fails before compiling it. + +Hint: not every shared-pointer type is safe to transfer to another thread. + +`Rc` is single-threaded reference counting and does not implement `Send`, so the compiler reports E0277 when the closure is passed to `thread::spawn`. `fixed.rs` uses `Arc`, whose atomic reference count is designed for cross-thread sharing. + +An alternative is to keep `Rc` when all ownership remains in one thread. `Arc` solves a thread-sharing requirement; it is not a drop-in performance upgrade for every `Rc`. diff --git a/labs/compiler-errors/send-sync/broken.rs b/labs/compiler-errors/send-sync/broken.rs new file mode 100644 index 0000000..ac32b70 --- /dev/null +++ b/labs/compiler-errors/send-sync/broken.rs @@ -0,0 +1,6 @@ +use std::rc::Rc; + +pub fn share_across_thread() { + let count = Rc::new(1); + std::thread::spawn(move || println!("{count}")); +} diff --git a/labs/compiler-errors/send-sync/expected-error.txt b/labs/compiler-errors/send-sync/expected-error.txt new file mode 100644 index 0000000..b40e5c9 --- /dev/null +++ b/labs/compiler-errors/send-sync/expected-error.txt @@ -0,0 +1 @@ +E0277 diff --git a/labs/compiler-errors/send-sync/fixed.rs b/labs/compiler-errors/send-sync/fixed.rs new file mode 100644 index 0000000..02758c9 --- /dev/null +++ b/labs/compiler-errors/send-sync/fixed.rs @@ -0,0 +1,7 @@ +use std::sync::Arc; + +pub fn share_across_thread() { + let count = Arc::new(1); + let handle = std::thread::spawn(move || println!("{count}")); + handle.join().expect("thread should complete"); +} diff --git a/labs/compiler-errors/trait-bound-not-satisfied/README.md b/labs/compiler-errors/trait-bound-not-satisfied/README.md new file mode 100644 index 0000000..dc7a4c3 --- /dev/null +++ b/labs/compiler-errors/trait-bound-not-satisfied/README.md @@ -0,0 +1,9 @@ +# Trait bound not satisfied + +The generic function wants to display a value. Predict why `broken.rs` fails before compiling it. + +Hint: a generic type parameter can stand for types with very different capabilities. + +Formatting with `{value}` requires `Display`, but unconstrained `T` does not promise that trait. The compiler reports E0277. `fixed.rs` makes the required capability explicit with the `T: Display` bound. + +An alternative is to format with `Debug` and require `T: Debug` when debug-style output is what the API means. Pick the bound that matches the operation, rather than adding bounds mechanically. diff --git a/labs/compiler-errors/trait-bound-not-satisfied/broken.rs b/labs/compiler-errors/trait-bound-not-satisfied/broken.rs new file mode 100644 index 0000000..1347ca5 --- /dev/null +++ b/labs/compiler-errors/trait-bound-not-satisfied/broken.rs @@ -0,0 +1,3 @@ +pub fn show(value: T) { + println!("{value}"); +} diff --git a/labs/compiler-errors/trait-bound-not-satisfied/expected-error.txt b/labs/compiler-errors/trait-bound-not-satisfied/expected-error.txt new file mode 100644 index 0000000..b40e5c9 --- /dev/null +++ b/labs/compiler-errors/trait-bound-not-satisfied/expected-error.txt @@ -0,0 +1 @@ +E0277 diff --git a/labs/compiler-errors/trait-bound-not-satisfied/fixed.rs b/labs/compiler-errors/trait-bound-not-satisfied/fixed.rs new file mode 100644 index 0000000..4208344 --- /dev/null +++ b/labs/compiler-errors/trait-bound-not-satisfied/fixed.rs @@ -0,0 +1,3 @@ +pub fn show(value: T) { + println!("{value}"); +} diff --git a/schemas/interview-category-v1.schema.json b/schemas/interview-category-v1.schema.json new file mode 100644 index 0000000..f7fb80c --- /dev/null +++ b/schemas/interview-category-v1.schema.json @@ -0,0 +1 @@ +{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://rust-learning-lab.dev/schemas/interview-category-v1.schema.json","title":"Rust Learning Lab interview category","type":"object","additionalProperties":false,"required":["schema_version","id","order","title","focus","levels","references"],"properties":{"$schema":{"type":"string"},"schema_version":{"const":1},"id":{"type":"string","pattern":"^[a-z0-9]+(?:-[a-z0-9]+)*$"},"order":{"type":"integer","minimum":1},"title":{"type":"string","minLength":1},"focus":{"type":"array","minItems":1,"items":{"type":"string","minLength":1}},"levels":{"type":"array","minItems":1,"uniqueItems":true,"items":{"enum":["foundation","working_rust_developer","senior_rust_developer","systems_performance_specialist"]}},"references":{"type":"array","minItems":1,"items":{"$ref":"#/$defs/reference"}}},"$defs":{"reference":{"type":"object","additionalProperties":false,"required":["title","path"],"properties":{"title":{"type":"string","minLength":1},"path":{"type":"string","minLength":1}}}}} diff --git a/schemas/interview-question-set-v1.schema.json b/schemas/interview-question-set-v1.schema.json new file mode 100644 index 0000000..c860dfa --- /dev/null +++ b/schemas/interview-question-set-v1.schema.json @@ -0,0 +1,42 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Rust Learning Lab interview question set", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "category", "questions"], + "properties": { + "schema_version": { "const": 1 }, + "category": { "type": "string" }, + "questions": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["id", "level", "focus", "prompt", "evaluation_criteria"], + "properties": { + "id": { "type": "string" }, + "level": { + "enum": [ + "foundation", + "working_rust_developer", + "senior_rust_developer", + "systems_performance_specialist" + ] + }, + "focus": { + "type": "array", + "minItems": 1, + "items": { "type": "string" } + }, + "prompt": { "type": "string", "minLength": 1 }, + "evaluation_criteria": { + "type": "array", + "minItems": 2, + "items": { "type": "string" } + } + } + } + } + } +} diff --git a/schemas/quiz-item-v1.schema.json b/schemas/quiz-item-v1.schema.json new file mode 100644 index 0000000..de0b68f --- /dev/null +++ b/schemas/quiz-item-v1.schema.json @@ -0,0 +1,52 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://rust-learning-lab.dev/schemas/quiz-item-v1.schema.json", + "title": "Rust Learning Lab quiz item", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "id", "type", "topic", "difficulty", "concepts", "question", "choices", "answer", "explanation", "references"], + "properties": { + "$schema": { "type": "string" }, + "schema_version": { "const": 1 }, + "id": { "type": "string", "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" }, + "type": { "enum": ["multiple_choice", "will_it_compile", "predict_output", "code_review", "fix_error", "design_choice"] }, + "topic": { "type": "string", "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" }, + "difficulty": { "enum": ["beginner", "intermediate", "advanced"] }, + "concepts": { "type": "array", "minItems": 1, "uniqueItems": true, "items": { "type": "string", "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" } }, + "question": { "type": "string", "minLength": 1 }, + "code": { "type": "string", "minLength": 1 }, + "choices": { "type": "array", "items": { "$ref": "#/$defs/choice" } }, + "answer": { "$ref": "#/$defs/answer" }, + "explanation": { "type": "string", "minLength": 1 }, + "references": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/reference" } } + }, + "$defs": { + "choice": { + "type": "object", + "additionalProperties": false, + "required": ["id", "text"], + "properties": { + "id": { "type": "string", "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" }, + "text": { "type": "string", "minLength": 1 } + } + }, + "answer": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "value"], + "properties": { + "kind": { "enum": ["choice", "compiles", "output", "review", "fix"] }, + "value": { "type": "string", "minLength": 1 } + } + }, + "reference": { + "type": "object", + "additionalProperties": false, + "required": ["title", "path"], + "properties": { + "title": { "type": "string", "minLength": 1 }, + "path": { "type": "string", "minLength": 1 } + } + } + } +} diff --git a/schemas/topic-metadata-v1.schema.json b/schemas/topic-metadata-v1.schema.json new file mode 100644 index 0000000..091cd82 --- /dev/null +++ b/schemas/topic-metadata-v1.schema.json @@ -0,0 +1,68 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Rust Learning Lab topic metadata", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "id", "title", "status", "level", "estimated_minutes", "prerequisites", "concepts", "tracks", "learning_objectives", "website", "validation"], + "properties": { + "$schema": { "type": "string" }, + "schema_version": { "const": 1 }, + "id": { "$ref": "#/$defs/slug" }, + "title": { "type": "string", "minLength": 1 }, + "status": { "enum": ["planned", "draft", "review", "stable", "deprecated"] }, + "level": { "enum": ["beginner", "intermediate", "advanced", "expert"] }, + "estimated_minutes": { "type": "integer", "minimum": 1 }, + "prerequisites": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/slug" } }, + "concepts": { "type": "array", "minItems": 1, "uniqueItems": true, "items": { "$ref": "#/$defs/slug" } }, + "tracks": { "type": "array", "minItems": 1, "uniqueItems": true, "items": { "enum": ["core", "java", "python", "cpp", "go"] } }, + "learning_objectives": { "type": "array", "minItems": 1, "items": { "type": "string", "minLength": 1 } }, + "website": { + "type": "object", + "additionalProperties": false, + "required": ["published", "order"], + "properties": { + "published": { "type": "boolean" }, + "order": { "type": ["integer", "null"], "minimum": 0 } + } + }, + "validation": { + "type": "object", + "additionalProperties": false, + "required": ["content_rubric", "examples", "exercises"], + "properties": { + "content_rubric": { "$ref": "#/$defs/evidence" }, + "examples": { "$ref": "#/$defs/evidence" }, + "exercises": { "$ref": "#/$defs/evidence" } + } + } + }, + "$defs": { + "slug": { "type": "string", "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" }, + "evidence": { "enum": ["not_applicable", "pending", "passed"] } + }, + "allOf": [ + { + "if": { "properties": { "website": { "properties": { "published": { "const": true } } } } }, + "then": { + "properties": { + "status": { "const": "stable" }, + "website": { "properties": { "order": { "type": "integer" } } } + } + } + }, + { + "if": { "properties": { "status": { "const": "stable" } } }, + "then": { + "properties": { + "validation": { + "properties": { + "content_rubric": { "const": "passed" }, + "examples": { "enum": ["not_applicable", "passed"] }, + "exercises": { "enum": ["not_applicable", "passed"] } + } + } + } + } + } + ] +} diff --git a/tools/contentctl/Cargo.lock b/tools/contentctl/Cargo.lock new file mode 100644 index 0000000..5fde596 --- /dev/null +++ b/tools/contentctl/Cargo.lock @@ -0,0 +1,212 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "contentctl" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tempfile", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6275cddf4610d1775e6d1fe9469b2e77d0f39fd98fb7450901b821e0c53649f" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/tools/contentctl/Cargo.toml b/tools/contentctl/Cargo.toml new file mode 100644 index 0000000..c99cd83 --- /dev/null +++ b/tools/contentctl/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "contentctl" +version = "0.1.0" +edition = "2021" +publish = false + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +[dev-dependencies] +tempfile = "3" diff --git a/tools/contentctl/src/lib.rs b/tools/contentctl/src/lib.rs new file mode 100644 index 0000000..13173cd --- /dev/null +++ b/tools/contentctl/src/lib.rs @@ -0,0 +1,985 @@ +use std::{ + collections::HashSet, + fs, + path::{Path, PathBuf}, +}; + +use serde::{Deserialize, Serialize}; + +const SCHEMA_VERSION: u32 = 1; +const QUIZ_SCHEMA_VERSION: u32 = 1; +const INTERVIEW_SCHEMA_VERSION: u32 = 1; +const INTERVIEW_QUESTION_SCHEMA_VERSION: u32 = 1; + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct TopicMetadata { + #[serde(rename = "$schema", default, skip_serializing)] + pub schema: Option, + pub schema_version: u32, + pub id: String, + pub title: String, + pub status: Status, + pub level: Level, + pub estimated_minutes: u32, + pub prerequisites: Vec, + pub concepts: Vec, + pub tracks: Vec, + pub learning_objectives: Vec, + pub website: Website, + pub validation: Validation, +} + +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum Status { + Planned, + Draft, + Review, + Stable, + Deprecated, +} + +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum Level { + Beginner, + Intermediate, + Advanced, + Expert, +} + +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "snake_case")] +pub enum Track { + Core, + Java, + Python, + Cpp, + Go, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Website { + pub published: bool, + pub order: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Validation { + pub content_rubric: Evidence, + pub examples: Evidence, + pub exercises: Evidence, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct QuizItem { + #[serde(rename = "$schema", default, skip_serializing)] + pub schema: Option, + pub schema_version: u32, + pub id: String, + #[serde(rename = "type")] + pub question_type: QuizType, + pub topic: String, + pub difficulty: QuizDifficulty, + pub concepts: Vec, + pub question: String, + pub code: Option, + pub choices: Vec, + pub answer: QuizAnswer, + pub explanation: String, + pub references: Vec, +} + +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum QuizType { + MultipleChoice, + WillItCompile, + PredictOutput, + CodeReview, + FixError, + DesignChoice, +} + +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum QuizDifficulty { + Beginner, + Intermediate, + Advanced, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct QuizChoice { + pub id: String, + pub text: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct QuizAnswer { + pub kind: QuizAnswerKind, + pub value: String, +} + +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum QuizAnswerKind { + Choice, + Compiles, + Output, + Review, + Fix, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct QuizReference { + pub title: String, + pub path: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct InterviewCategory { + #[serde(rename = "$schema", default, skip_serializing)] + pub schema: Option, + pub schema_version: u32, + pub id: String, + pub order: u32, + pub title: String, + pub focus: Vec, + pub levels: Vec, + pub references: Vec, +} + +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "snake_case")] +pub enum InterviewLevel { + Foundation, + WorkingRustDeveloper, + SeniorRustDeveloper, + SystemsPerformanceSpecialist, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct InterviewQuestionSet { + #[serde(rename = "$schema", default, skip_serializing)] + pub schema: Option, + pub schema_version: u32, + pub category: String, + pub questions: Vec, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct InterviewQuestion { + pub id: String, + pub level: InterviewLevel, + pub focus: Vec, + pub prompt: String, + pub evaluation_criteria: Vec, +} + +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum Evidence { + NotApplicable, + Pending, + Passed, +} + +#[derive(Debug, Serialize)] +struct ExportedTopic { + source_path: String, + #[serde(flatten)] + metadata: TopicMetadata, +} + +pub fn validate_path(path: &Path) -> Result, Vec> { + let files = metadata_files(path).map_err(|error| vec![error])?; + if files.is_empty() { + return Err(vec![format!( + "{} contains no topic metadata JSON files", + path.display() + )]); + } + + let mut topics = Vec::new(); + let mut errors = Vec::new(); + + for file in files { + match parse_file(&file) { + Ok((metadata, mut file_errors)) => { + topics.push((file, metadata)); + errors.append(&mut file_errors); + } + Err(mut file_errors) => errors.append(&mut file_errors), + } + } + + let mut ids = HashSet::new(); + for (file, topic) in &topics { + if !ids.insert(&topic.id) { + errors.push(format!( + "{}: duplicate topic id `{}`", + file.display(), + topic.id + )); + } + } + + for (file, topic) in &topics { + if topic.website.published { + for prerequisite in &topic.prerequisites { + if !ids.contains(prerequisite) { + errors.push(format!( + "{}: published topic prerequisite `{prerequisite}` has no metadata in this validation scope", + file.display() + )); + } + } + } + } + + if errors.is_empty() { + topics.sort_by(|left, right| left.1.id.cmp(&right.1.id).then(left.0.cmp(&right.0))); + Ok(topics) + } else { + Err(errors) + } +} + +pub fn export_path(path: &Path) -> Result> { + let topics = validate_path(path)?; + let directory_root = path.is_dir().then_some(path); + let exported: Vec<_> = topics + .into_iter() + .map(|(source_path, metadata)| ExportedTopic { + source_path: normalized_path( + directory_root + .and_then(|root| source_path.strip_prefix(root).ok()) + .unwrap_or(&source_path), + ), + metadata, + }) + .collect(); + + serde_json::to_string_pretty(&exported) + .map(|json| format!("{json}\n")) + .map_err(|error| vec![format!("could not serialize export: {error}")]) +} + +pub fn validate_file(path: &Path) -> Result> { + let (metadata, errors) = parse_file(path)?; + + if errors.is_empty() { + Ok(metadata) + } else { + Err(errors) + } +} + +pub fn validate_quiz_path(path: &Path) -> Result, Vec> { + let files = quiz_files(path).map_err(|error| vec![error])?; + if files.is_empty() { + return Err(vec![format!( + "{} contains no quiz item JSON files", + path.display() + )]); + } + + let mut items = Vec::new(); + let mut errors = Vec::new(); + for file in files { + match parse_quiz_file(&file) { + Ok((item, mut item_errors)) => { + items.push((file, item)); + errors.append(&mut item_errors); + } + Err(mut item_errors) => errors.append(&mut item_errors), + } + } + + let mut ids = HashSet::new(); + for (file, item) in &items { + if !ids.insert(&item.id) { + errors.push(format!( + "{}: duplicate quiz item id `{}`", + file.display(), + item.id + )); + } + } + + if errors.is_empty() { + items.sort_by(|left, right| left.1.id.cmp(&right.1.id)); + Ok(items) + } else { + Err(errors) + } +} + +pub fn validate_quiz_file(path: &Path) -> Result> { + let (item, errors) = parse_quiz_file(path)?; + if errors.is_empty() { + Ok(item) + } else { + Err(errors) + } +} + +pub fn validate_interview_path( + path: &Path, +) -> Result, Vec> { + let files = interview_files(path).map_err(|error| vec![error])?; + if files.is_empty() { + return Err(vec![format!( + "{} contains no interview category JSON files", + path.display() + )]); + } + let mut categories = Vec::new(); + let mut errors = Vec::new(); + for file in files { + match parse_interview_file(&file) { + Ok((category, mut category_errors)) => { + categories.push((file, category)); + errors.append(&mut category_errors); + } + Err(mut category_errors) => errors.append(&mut category_errors), + } + } + let mut ids = HashSet::new(); + let mut orders = HashSet::new(); + for (file, category) in &categories { + if !ids.insert(&category.id) { + errors.push(format!( + "{}: duplicate interview category id `{}`", + file.display(), + category.id + )); + } + if !orders.insert(category.order) { + errors.push(format!( + "{}: duplicate interview category order `{}`", + file.display(), + category.order + )); + } + } + if orders.len() == categories.len() + && !(1..=categories.len() as u32).all(|order| orders.contains(&order)) + { + errors.push("interview category order must be contiguous starting at 1".to_owned()); + } + if errors.is_empty() { + categories.sort_by_key(|(_, category)| category.order); + Ok(categories) + } else { + Err(errors) + } +} + +pub fn validate_interview_questions_path( + path: &Path, + taxonomy_path: &Path, +) -> Result, Vec> { + let categories = validate_interview_path(taxonomy_path)?; + let category_ids: HashSet<_> = categories + .iter() + .map(|(_, category)| category.id.as_str()) + .collect(); + let files = interview_files(path).map_err(|error| vec![error])?; + if files.is_empty() { + return Err(vec![format!( + "{} contains no interview question-set JSON files", + path.display() + )]); + } + let mut questions = Vec::new(); + let mut errors = Vec::new(); + for file in files { + match parse_interview_question_file(&file) { + Ok((set, mut set_errors)) => { + if !category_ids.contains(set.category.as_str()) { + set_errors.push(format!( + "{}: category `{}` is not defined by the interview taxonomy", + file.display(), + set.category + )); + } + questions.extend( + set.questions + .into_iter() + .map(|question| (file.clone(), question)), + ); + errors.append(&mut set_errors); + } + Err(mut file_errors) => errors.append(&mut file_errors), + } + } + let mut ids = HashSet::new(); + for (file, question) in &questions { + if !ids.insert(&question.id) { + errors.push(format!( + "{}: duplicate interview question id `{}`", + file.display(), + question.id + )); + } + } + if errors.is_empty() { + questions.sort_by(|left, right| left.1.id.cmp(&right.1.id)); + Ok(questions) + } else { + Err(errors) + } +} + +pub fn unresolved_prerequisites(topics: &[(PathBuf, TopicMetadata)]) -> Vec<(String, String)> { + let ids: HashSet<_> = topics.iter().map(|(_, topic)| topic.id.as_str()).collect(); + let mut unresolved = topics + .iter() + .flat_map(|(_, topic)| { + topic + .prerequisites + .iter() + .filter(|prerequisite| !ids.contains(prerequisite.as_str())) + .map(|prerequisite| (topic.id.clone(), prerequisite.clone())) + }) + .collect::>(); + unresolved.sort(); + unresolved +} + +fn parse_file(path: &Path) -> Result<(TopicMetadata, Vec), Vec> { + let contents = fs::read_to_string(path) + .map_err(|error| vec![format!("{}: could not read file: {error}", path.display())])?; + let metadata: TopicMetadata = serde_json::from_str(&contents) + .map_err(|error| vec![format!("{}: invalid metadata: {error}", path.display())])?; + let errors = semantic_errors(path, &metadata); + Ok((metadata, errors)) +} + +fn parse_quiz_file(path: &Path) -> Result<(QuizItem, Vec), Vec> { + let contents = fs::read_to_string(path) + .map_err(|error| vec![format!("{}: could not read file: {error}", path.display())])?; + let item: QuizItem = serde_json::from_str(&contents) + .map_err(|error| vec![format!("{}: invalid quiz item: {error}", path.display())])?; + let errors = quiz_semantic_errors(path, &item); + Ok((item, errors)) +} + +fn parse_interview_file(path: &Path) -> Result<(InterviewCategory, Vec), Vec> { + let contents = fs::read_to_string(path) + .map_err(|error| vec![format!("{}: could not read file: {error}", path.display())])?; + let category: InterviewCategory = serde_json::from_str(&contents).map_err(|error| { + vec![format!( + "{}: invalid interview category: {error}", + path.display() + )] + })?; + let errors = interview_semantic_errors(path, &category); + Ok((category, errors)) +} + +fn parse_interview_question_file( + path: &Path, +) -> Result<(InterviewQuestionSet, Vec), Vec> { + let contents = fs::read_to_string(path) + .map_err(|error| vec![format!("{}: could not read file: {error}", path.display())])?; + let set: InterviewQuestionSet = serde_json::from_str(&contents).map_err(|error| { + vec![format!( + "{}: invalid interview question set: {error}", + path.display() + )] + })?; + let errors = interview_question_set_errors(path, &set); + Ok((set, errors)) +} + +fn metadata_files(path: &Path) -> Result, String> { + if path.is_file() { + return Ok(vec![path.to_path_buf()]); + } + if !path.is_dir() { + return Err(format!("{} is not a file or directory", path.display())); + } + + let mut files = Vec::new(); + collect_metadata_files(path, &mut files)?; + files.sort(); + Ok(files) +} + +fn quiz_files(path: &Path) -> Result, String> { + if path.is_file() { + return Ok(vec![path.to_path_buf()]); + } + if !path.is_dir() { + return Err(format!("{} is not a file or directory", path.display())); + } + + let mut files = Vec::new(); + collect_quiz_files(path, &mut files)?; + files.sort(); + Ok(files) +} + +fn interview_files(path: &Path) -> Result, String> { + if path.is_file() { + return Ok(vec![path.to_path_buf()]); + } + if !path.is_dir() { + return Err(format!("{} is not a file or directory", path.display())); + } + let mut files = Vec::new(); + collect_quiz_files(path, &mut files)?; + files.sort(); + Ok(files) +} + +fn collect_metadata_files(directory: &Path, files: &mut Vec) -> Result<(), String> { + let entries = fs::read_dir(directory) + .map_err(|error| format!("{}: could not read directory: {error}", directory.display()))?; + + for entry in entries { + let entry = entry.map_err(|error| format!("{}: {error}", directory.display()))?; + let path = entry.path(); + if path.is_dir() { + if path + .file_name() + .is_some_and(|name| name == "target" || name == ".git") + { + continue; + } + collect_metadata_files(&path, files)?; + } else if path.file_name().is_some_and(|name| name == "metadata.json") { + files.push(path); + } + } + + Ok(()) +} + +fn collect_quiz_files(directory: &Path, files: &mut Vec) -> Result<(), String> { + let entries = fs::read_dir(directory) + .map_err(|error| format!("{}: could not read directory: {error}", directory.display()))?; + for entry in entries { + let entry = entry.map_err(|error| format!("{}: {error}", directory.display()))?; + let path = entry.path(); + if path.is_dir() { + if path + .file_name() + .is_some_and(|name| name == "target" || name == ".git") + { + continue; + } + collect_quiz_files(&path, files)?; + } else if path + .extension() + .is_some_and(|extension| extension == "json") + { + files.push(path); + } + } + Ok(()) +} + +fn semantic_errors(path: &Path, metadata: &TopicMetadata) -> Vec { + let mut errors = Vec::new(); + let prefix = || path.display().to_string(); + + if metadata.schema_version != SCHEMA_VERSION { + errors.push(format!( + "{}: schema_version must be {SCHEMA_VERSION}", + prefix() + )); + } + if !is_slug(&metadata.id) { + errors.push(format!( + "{}: id must be a lowercase kebab-case slug", + prefix() + )); + } + if metadata.title.trim().is_empty() { + errors.push(format!("{}: title must not be empty", prefix())); + } + if metadata.estimated_minutes == 0 { + errors.push(format!( + "{}: estimated_minutes must be greater than zero", + prefix() + )); + } + validate_unique_slugs(path, "prerequisites", &metadata.prerequisites, &mut errors); + validate_unique_slugs(path, "concepts", &metadata.concepts, &mut errors); + validate_non_empty(path, "concepts", &metadata.concepts, &mut errors); + validate_non_empty( + path, + "learning_objectives", + &metadata.learning_objectives, + &mut errors, + ); + + if metadata.prerequisites.iter().any(|id| id == &metadata.id) { + errors.push(format!("{}: a topic cannot require itself", prefix())); + } + if metadata.tracks.is_empty() { + errors.push(format!( + "{}: tracks must contain at least one entry", + prefix() + )); + } + if metadata + .tracks + .iter() + .copied() + .collect::>() + .len() + != metadata.tracks.len() + { + errors.push(format!("{}: tracks must not contain duplicates", prefix())); + } + if metadata + .learning_objectives + .iter() + .any(|objective| objective.trim().is_empty()) + { + errors.push(format!( + "{}: learning_objectives must not contain empty text", + prefix() + )); + } + if metadata.website.published && metadata.status != Status::Stable { + errors.push(format!("{}: only Stable topics may be published", prefix())); + } + if metadata.website.published && metadata.website.order.is_none() { + errors.push(format!( + "{}: a published topic requires website.order", + prefix() + )); + } + if metadata.status == Status::Stable + && (metadata.validation.content_rubric != Evidence::Passed + || !matches!( + metadata.validation.examples, + Evidence::Passed | Evidence::NotApplicable + ) + || !matches!( + metadata.validation.exercises, + Evidence::Passed | Evidence::NotApplicable + )) + { + errors.push(format!("{}: Stable requires a passed content rubric and passed or not-applicable automated evidence", prefix())); + } + + errors +} + +fn quiz_semantic_errors(path: &Path, item: &QuizItem) -> Vec { + let mut errors = Vec::new(); + let prefix = || path.display().to_string(); + if item.schema_version != QUIZ_SCHEMA_VERSION { + errors.push(format!( + "{}: schema_version must be {QUIZ_SCHEMA_VERSION}", + prefix() + )); + } + if !is_slug(&item.id) { + errors.push(format!( + "{}: id must be a lowercase kebab-case slug", + prefix() + )); + } + if !is_slug(&item.topic) { + errors.push(format!( + "{}: topic must be a lowercase kebab-case slug", + prefix() + )); + } + validate_non_empty(path, "concepts", &item.concepts, &mut errors); + validate_unique_slugs(path, "concepts", &item.concepts, &mut errors); + if item.question.trim().is_empty() { + errors.push(format!("{}: question must not be empty", prefix())); + } + if item.explanation.trim().is_empty() { + errors.push(format!("{}: explanation must not be empty", prefix())); + } + if item.references.is_empty() { + errors.push(format!( + "{}: references must contain at least one entry", + prefix() + )); + } + for reference in &item.references { + if reference.title.trim().is_empty() || reference.path.trim().is_empty() { + errors.push(format!( + "{}: references must have non-empty title and path", + prefix() + )); + } + } + if item + .code + .as_ref() + .is_some_and(|code| code.trim().is_empty()) + { + errors.push(format!( + "{}: code must not be empty when supplied", + prefix() + )); + } + + let code_required = matches!( + item.question_type, + QuizType::WillItCompile + | QuizType::PredictOutput + | QuizType::CodeReview + | QuizType::FixError + ); + if code_required && item.code.is_none() { + errors.push(format!("{}: this question type requires code", prefix())); + } + let choice_required = matches!( + item.question_type, + QuizType::MultipleChoice | QuizType::DesignChoice + ); + if choice_required && item.choices.len() < 2 { + errors.push(format!( + "{}: this question type requires at least two choices", + prefix() + )); + } + if !choice_required && !item.choices.is_empty() { + errors.push(format!( + "{}: only choice questions may define choices", + prefix() + )); + } + let mut choice_ids = HashSet::new(); + for choice in &item.choices { + if !is_slug(&choice.id) || choice.text.trim().is_empty() { + errors.push(format!( + "{}: choices require a slug id and non-empty text", + prefix() + )); + } + if !choice_ids.insert(&choice.id) { + errors.push(format!( + "{}: choice id `{}` is duplicated", + prefix(), + choice.id + )); + } + } + + let expected_answer = match item.question_type { + QuizType::MultipleChoice | QuizType::DesignChoice => QuizAnswerKind::Choice, + QuizType::WillItCompile => QuizAnswerKind::Compiles, + QuizType::PredictOutput => QuizAnswerKind::Output, + QuizType::CodeReview => QuizAnswerKind::Review, + QuizType::FixError => QuizAnswerKind::Fix, + }; + if item.answer.kind != expected_answer { + errors.push(format!( + "{}: answer kind does not match question type", + prefix() + )); + } + if item.answer.value.trim().is_empty() { + errors.push(format!("{}: answer value must not be empty", prefix())); + } + if item.answer.kind == QuizAnswerKind::Choice && !choice_ids.contains(&item.answer.value) { + errors.push(format!( + "{}: answer choice `{}` is not defined", + prefix(), + item.answer.value + )); + } + if item.answer.kind == QuizAnswerKind::Compiles + && !matches!(item.answer.value.as_str(), "true" | "false") + { + errors.push(format!( + "{}: compiles answer must be `true` or `false`", + prefix() + )); + } + errors +} + +fn interview_semantic_errors(path: &Path, category: &InterviewCategory) -> Vec { + let mut errors = Vec::new(); + if category.schema_version != INTERVIEW_SCHEMA_VERSION { + errors.push(format!( + "{}: schema_version must be {INTERVIEW_SCHEMA_VERSION}", + path.display() + )); + } + if !is_slug(&category.id) { + errors.push(format!( + "{}: id must be a lowercase kebab-case slug", + path.display() + )); + } + if category.order == 0 { + errors.push(format!( + "{}: order must be greater than zero", + path.display() + )); + } + if category.title.trim().is_empty() { + errors.push(format!("{}: title must not be empty", path.display())); + } + validate_non_empty(path, "focus", &category.focus, &mut errors); + if category.focus.iter().any(|focus| focus.trim().is_empty()) { + errors.push(format!( + "{}: focus must not contain empty text", + path.display() + )); + } + if category.levels.is_empty() { + errors.push(format!( + "{}: levels must contain at least one entry", + path.display() + )); + } + if category + .levels + .iter() + .copied() + .collect::>() + .len() + != category.levels.len() + { + errors.push(format!( + "{}: levels must not contain duplicates", + path.display() + )); + } + if category.references.is_empty() { + errors.push(format!( + "{}: references must contain at least one entry", + path.display() + )); + } + for reference in &category.references { + if reference.title.trim().is_empty() || reference.path.trim().is_empty() { + errors.push(format!( + "{}: references must have non-empty title and path", + path.display() + )); + } + } + errors +} + +fn interview_question_set_errors(path: &Path, set: &InterviewQuestionSet) -> Vec { + let mut errors = Vec::new(); + if set.schema_version != INTERVIEW_QUESTION_SCHEMA_VERSION { + errors.push(format!( + "{}: schema_version must be {INTERVIEW_QUESTION_SCHEMA_VERSION}", + path.display() + )); + } + if !is_slug(&set.category) { + errors.push(format!( + "{}: category must be a lowercase kebab-case slug", + path.display() + )); + } + if set.questions.is_empty() { + errors.push(format!( + "{}: questions must contain at least one entry", + path.display() + )); + } + for question in &set.questions { + if !is_slug(&question.id) { + errors.push(format!( + "{}: question id must be a lowercase kebab-case slug", + path.display() + )); + } + validate_non_empty(path, "question focus", &question.focus, &mut errors); + if question.focus.iter().any(|focus| focus.trim().is_empty()) { + errors.push(format!( + "{}: question focus must not contain empty text", + path.display() + )); + } + if question.prompt.trim().is_empty() { + errors.push(format!( + "{}: question prompt must not be empty", + path.display() + )); + } + if question.evaluation_criteria.len() < 2 { + errors.push(format!( + "{}: question evaluation_criteria must contain at least two entries", + path.display() + )); + } + if question + .evaluation_criteria + .iter() + .any(|criterion| criterion.trim().is_empty()) + { + errors.push(format!( + "{}: question evaluation_criteria must not contain empty text", + path.display() + )); + } + } + errors +} + +fn validate_unique_slugs(path: &Path, field: &str, values: &[String], errors: &mut Vec) { + let mut seen = HashSet::new(); + for value in values { + if !is_slug(value) { + errors.push(format!( + "{}: {field} entry `{value}` must be a lowercase kebab-case slug", + path.display() + )); + } + if !seen.insert(value) { + errors.push(format!( + "{}: {field} entry `{value}` is duplicated", + path.display() + )); + } + } +} + +fn validate_non_empty(path: &Path, field: &str, values: &[String], errors: &mut Vec) { + if values.is_empty() { + errors.push(format!( + "{}: {field} must contain at least one entry", + path.display() + )); + } +} + +fn is_slug(value: &str) -> bool { + !value.is_empty() + && !value.starts_with('-') + && !value.ends_with('-') + && value + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') + && !value.contains("--") +} + +fn normalized_path(path: &Path) -> String { + path.components() + .map(|component| component.as_os_str().to_string_lossy()) + .collect::>() + .join("/") +} diff --git a/tools/contentctl/src/main.rs b/tools/contentctl/src/main.rs new file mode 100644 index 0000000..caef78d --- /dev/null +++ b/tools/contentctl/src/main.rs @@ -0,0 +1,73 @@ +use std::{env, path::PathBuf, process::ExitCode}; + +use contentctl::{ + export_path, unresolved_prerequisites, validate_interview_path, + validate_interview_questions_path, validate_path, validate_quiz_path, +}; + +fn main() -> ExitCode { + match run() { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("contentctl: {error}"); + ExitCode::FAILURE + } + } +} + +fn run() -> Result<(), String> { + let mut args = env::args().skip(1); + let command = args.next().ok_or_else(usage)?; + let path = PathBuf::from(args.next().ok_or_else(usage)?); + + let extra_path = args.next().map(PathBuf::from); + + if extra_path.is_some() && args.next().is_some() { + return Err(usage()); + } + if command != "validate-interview-questions" && extra_path.is_some() { + return Err(usage()); + } + + match command.as_str() { + "validate" => { + let topics = validate_path(&path).map_err(|errors| errors.join("\n"))?; + for (topic, prerequisite) in unresolved_prerequisites(&topics) { + eprintln!( + "contentctl: warning: topic `{topic}` references `{prerequisite}`, which has no metadata in this validation scope" + ); + } + println!("Validated {} topic metadata file(s).", topics.len()); + Ok(()) + } + "export" => { + let json = export_path(&path).map_err(|errors| errors.join("\n"))?; + println!("{json}"); + Ok(()) + } + "validate-quiz" => { + let items = validate_quiz_path(&path).map_err(|errors| errors.join("\n"))?; + println!("Validated {} quiz item(s).", items.len()); + Ok(()) + } + "validate-interview" => { + let categories = validate_interview_path(&path).map_err(|errors| errors.join("\n"))?; + println!("Validated {} interview category file(s).", categories.len()); + Ok(()) + } + "validate-interview-questions" => { + let taxonomy_path = extra_path.ok_or_else(usage)?; + let questions = validate_interview_questions_path(&path, &taxonomy_path) + .map_err(|errors| errors.join("\n"))?; + println!("Validated {} interview question(s).", questions.len()); + Ok(()) + } + _ if extra_path.is_some() => Err(usage()), + _ => Err(usage()), + } +} + +fn usage() -> String { + "usage: contentctl \n contentctl validate-interview-questions " + .to_owned() +} diff --git a/tools/contentctl/tests/validation.rs b/tools/contentctl/tests/validation.rs new file mode 100644 index 0000000..b09629d --- /dev/null +++ b/tools/contentctl/tests/validation.rs @@ -0,0 +1,299 @@ +use std::{fs, path::Path}; + +use contentctl::{ + export_path, unresolved_prerequisites, validate_file, validate_interview_path, + validate_interview_questions_path, validate_path, validate_quiz_file, validate_quiz_path, +}; +use serde_json::{json, Value}; +use tempfile::tempdir; + +fn valid_topic(id: &str) -> Value { + json!({ + "schema_version": 1, + "id": id, + "title": "A useful topic", + "status": "review", + "level": "beginner", + "estimated_minutes": 30, + "prerequisites": [], + "concepts": ["rust"], + "tracks": ["core"], + "learning_objectives": ["Explain the demonstrated Rust concept."], + "website": { "published": false, "order": null }, + "validation": { + "content_rubric": "pending", + "examples": "passed", + "exercises": "not_applicable" + } + }) +} + +fn write_topic(path: &Path, value: &Value) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, serde_json::to_vec_pretty(value).unwrap()).unwrap(); +} + +fn valid_quiz(id: &str) -> Value { + json!({ + "schema_version": 1, + "id": id, + "type": "multiple_choice", + "topic": "ownership", + "difficulty": "beginner", + "concepts": ["ownership"], + "question": "Which choice is correct?", + "choices": [ + { "id": "correct", "text": "The correct choice" }, + { "id": "incorrect", "text": "The incorrect choice" } + ], + "answer": { "kind": "choice", "value": "correct" }, + "explanation": "It matches the stated rule.", + "references": [{ "title": "Ownership", "path": "README.md" }] + }) +} + +fn write_quiz(path: &Path, value: &Value) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, serde_json::to_vec_pretty(value).unwrap()).unwrap(); +} + +fn published_stable_topic(id: &str) -> Value { + let mut topic = valid_topic(id); + topic["status"] = json!("stable"); + topic["website"] = json!({ "published": true, "order": 10 }); + topic["validation"] = json!({ + "content_rubric": "passed", + "examples": "passed", + "exercises": "not_applicable" + }); + topic +} + +#[test] +fn accepts_the_documented_example() { + let path = Path::new("../../docs/examples/topic-metadata.json"); + let metadata = validate_file(path).unwrap(); + assert_eq!(metadata.id, "ownership-borrowing"); +} + +#[test] +fn rejects_unknown_fields() { + let directory = tempdir().unwrap(); + let path = directory.path().join("metadata.json"); + let mut topic = valid_topic("unknown-field"); + topic["unexpected"] = json!(true); + write_topic(&path, &topic); + + let errors = validate_file(&path).unwrap_err(); + assert!(errors.join("\n").contains("unknown field `unexpected`")); +} + +#[test] +fn rejects_stable_topic_without_complete_evidence() { + let directory = tempdir().unwrap(); + let path = directory.path().join("metadata.json"); + let mut topic = valid_topic("premature-stable"); + topic["status"] = json!("stable"); + write_topic(&path, &topic); + + let errors = validate_file(&path).unwrap_err(); + assert!(errors + .join("\n") + .contains("Stable requires a passed content rubric")); +} + +#[test] +fn rejects_publishing_non_stable_content() { + let directory = tempdir().unwrap(); + let path = directory.path().join("metadata.json"); + let mut topic = valid_topic("unreviewed-publication"); + topic["website"] = json!({ "published": true, "order": 10 }); + write_topic(&path, &topic); + + let errors = validate_file(&path).unwrap_err(); + assert!(errors + .join("\n") + .contains("only Stable topics may be published")); +} + +#[test] +fn rejects_duplicate_ids_in_a_directory() { + let directory = tempdir().unwrap(); + write_topic( + &directory.path().join("one/metadata.json"), + &valid_topic("same-id"), + ); + write_topic( + &directory.path().join("two/metadata.json"), + &valid_topic("same-id"), + ); + + let errors = validate_path(directory.path()).unwrap_err(); + assert!(errors.join("\n").contains("duplicate topic id `same-id`")); +} + +#[test] +fn rejects_duplicate_ids_even_when_one_file_has_other_validation_errors() { + let directory = tempdir().unwrap(); + write_topic( + &directory.path().join("one/metadata.json"), + &valid_topic("same-id"), + ); + let mut invalid_duplicate = valid_topic("same-id"); + invalid_duplicate["estimated_minutes"] = json!(0); + write_topic( + &directory.path().join("two/metadata.json"), + &invalid_duplicate, + ); + + let errors = validate_path(directory.path()).unwrap_err().join("\n"); + assert!(errors.contains("estimated_minutes must be greater than zero")); + assert!(errors.contains("duplicate topic id `same-id`")); +} + +#[test] +fn rejects_a_published_topic_with_an_unmigrated_prerequisite() { + let directory = tempdir().unwrap(); + let mut topic = published_stable_topic("published-topic"); + topic["prerequisites"] = json!(["missing-topic"]); + write_topic(&directory.path().join("metadata.json"), &topic); + + let errors = validate_path(directory.path()).unwrap_err().join("\n"); + assert!(errors.contains("published topic prerequisite `missing-topic` has no metadata")); +} + +#[test] +fn accepts_a_published_topic_with_a_migrated_prerequisite() { + let directory = tempdir().unwrap(); + write_topic( + &directory.path().join("required/metadata.json"), + &published_stable_topic("required-topic"), + ); + let mut topic = published_stable_topic("published-topic"); + topic["website"]["order"] = json!(20); + topic["prerequisites"] = json!(["required-topic"]); + write_topic(&directory.path().join("published/metadata.json"), &topic); + + assert!(validate_path(directory.path()).is_ok()); +} + +#[test] +fn reports_unmigrated_prerequisites_without_blocking_unpublished_topics() { + let directory = tempdir().unwrap(); + let mut topic = valid_topic("review-topic"); + topic["prerequisites"] = json!(["future-topic"]); + write_topic(&directory.path().join("metadata.json"), &topic); + + let topics = validate_path(directory.path()).unwrap(); + assert_eq!( + unresolved_prerequisites(&topics), + vec![("review-topic".to_owned(), "future-topic".to_owned())] + ); +} + +#[test] +fn export_is_sorted_and_deterministic() { + let directory = tempdir().unwrap(); + write_topic( + &directory.path().join("z/metadata.json"), + &valid_topic("z-last"), + ); + write_topic( + &directory.path().join("a/metadata.json"), + &valid_topic("a-first"), + ); + + let first = export_path(directory.path()).unwrap(); + let second = export_path(directory.path()).unwrap(); + assert_eq!(first, second); + assert!(first.find("a-first").unwrap() < first.find("z-last").unwrap()); + assert!(!first.contains(&directory.path().to_string_lossy().to_string())); + assert!(first.contains("a/metadata.json")); +} + +#[test] +fn accepts_the_first_foundation_quiz_item() { + let path = Path::new("../../challenges/quiz-items/01-mutability-binding.json"); + let item = validate_quiz_file(path).unwrap(); + assert_eq!(item.id, "quiz-mutability-binding"); +} + +#[test] +fn accepts_all_fifty_foundation_quiz_items() { + let items = validate_quiz_path(Path::new("../../challenges/quiz-items")).unwrap(); + assert_eq!(items.len(), 50); +} + +#[test] +fn foundation_set_includes_compile_prediction_challenges() { + let items = validate_quiz_path(Path::new("../../challenges/quiz-items")).unwrap(); + let compile_predictions = items + .iter() + .filter(|(_, item)| item.question_type == contentctl::QuizType::WillItCompile) + .count(); + assert!(compile_predictions >= 10); +} + +#[test] +fn accepts_all_code_review_challenges() { + let items = validate_quiz_path(Path::new("../../challenges/code-review/items")).unwrap(); + assert_eq!(items.len(), 6); + assert!(items + .iter() + .all(|(_, item)| item.question_type == contentctl::QuizType::CodeReview)); +} + +#[test] +fn accepts_the_eleven_interview_categories_in_order() { + let categories = + validate_interview_path(Path::new("../../challenges/interview/taxonomy")).unwrap(); + assert_eq!(categories.len(), 11); + assert_eq!(categories.first().unwrap().1.id, "language-fundamentals"); + assert_eq!(categories.last().unwrap().1.id, "code-review"); +} + +#[test] +fn accepts_one_hundred_interview_questions() { + let questions = validate_interview_questions_path( + Path::new("../../challenges/interview/questions"), + Path::new("../../challenges/interview/taxonomy"), + ) + .unwrap(); + assert_eq!(questions.len(), 100); +} + +#[test] +fn rejects_choice_questions_without_a_valid_answer_choice() { + let directory = tempdir().unwrap(); + let path = directory.path().join("quiz.json"); + let mut quiz = valid_quiz("bad-answer"); + quiz["answer"]["value"] = json!("missing"); + write_quiz(&path, &quiz); + + let errors = validate_quiz_file(&path).unwrap_err().join("\n"); + assert!(errors.contains("answer choice `missing` is not defined")); +} + +#[test] +fn rejects_code_questions_without_code() { + let directory = tempdir().unwrap(); + let path = directory.path().join("quiz.json"); + let mut quiz = valid_quiz("missing-code"); + quiz["type"] = json!("will_it_compile"); + quiz["choices"] = json!([]); + quiz["answer"] = json!({ "kind": "compiles", "value": "true" }); + write_quiz(&path, &quiz); + + let errors = validate_quiz_file(&path).unwrap_err().join("\n"); + assert!(errors.contains("this question type requires code")); +} + +#[test] +fn rejects_duplicate_quiz_ids_in_a_directory() { + let directory = tempdir().unwrap(); + write_quiz(&directory.path().join("one.json"), &valid_quiz("same-quiz")); + write_quiz(&directory.path().join("two.json"), &valid_quiz("same-quiz")); + + let errors = validate_quiz_path(directory.path()).unwrap_err().join("\n"); + assert!(errors.contains("duplicate quiz item id `same-quiz`")); +}