Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Chapter 2: Exploring Rust Basics #188

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

SniperXyZ011
Copy link

@SniperXyZ011 SniperXyZ011 commented Dec 21, 2024

Description

This pull request adds Chapter 2 to the book-compendium section of the repository. It includes the following examples:

  • variables.rs: Demonstrates variable immutability and mutability in Rust.
  • control_flow.rs: Explains basic control flow constructs like if-else and loops.
  • ownership.rs: Introduces Rust's ownership model and function interactions.

Summary by CodeRabbit

  • New Features

    • Introduced a new README file for Chapter 2: "Exploring Rust Basics," outlining key Rust concepts with examples.
    • Added new sections demonstrating variables, control flow, and ownership in Rust.
    • Implemented examples for basic control flow, ownership, and variable mutability in separate Rust files.
  • Bug Fixes

    • Corrected the filename from varible.rs to variable.rs for consistency.

Copy link

vercel bot commented Dec 21, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
rustcrab ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 21, 2024 11:00am

Copy link
Contributor

coderabbitai bot commented Dec 21, 2024

Walkthrough

This pull request introduces a new chapter (Chapter 2) in a book compendium focusing on Rust programming basics. The chapter includes four files: a README and three Rust source files (control_flow.rs, ownership.rs, and varible.rs). These files collectively demonstrate fundamental Rust concepts such as variable declaration, control flow, and the ownership model, providing a structured introduction to key language features through practical code examples.

Changes

File Change Summary
book-compendium/chapter-2/README.md Added new chapter README with overview of Rust basics
book-compendium/chapter-2/control_flow.rs New file demonstrating Rust control flow with if statement and for loop
book-compendium/chapter-2/ownership.rs New file illustrating Rust's ownership concept with string transfer
book-compendium/chapter-2/varible.rs New file showing immutable and mutable variable usage

Sequence Diagram

sequenceDiagram
    participant Main as main()
    participant TakeOwnership as take_ownership()
    
    Main->>Main: Create String "Hello, Ownership!"
    Main->>TakeOwnership: Transfer string ownership
    TakeOwnership-->>TakeOwnership: Print string
    TakeOwnership--xMain: Original string no longer valid
Loading

Poem

🐰 Rust's Rabbit Rhapsody 🦀

In Chapter Two, we hop and learn,
Of variables that twist and turn,
Ownership tight, control flow bright,
A coding dance of pure delight!
Rust's magic, simple yet profound.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (4)
book-compendium/chapter-2/varibles.rs (1)

1-9: Consider enhancing the educational value with more detailed comments

While the code effectively demonstrates variable mutability, consider adding more detailed comments to better explain the concepts for learners. This could include:

  • Why Rust defaults to immutable variables
  • When to use mutable variables
  • Best practices around mutability

Here's a suggested enhancement:

 fn main() {
-    let x = 5; // Immutable variable
+    // By default, variables in Rust are immutable (cannot be changed)
+    // This promotes safer and more predictable code
+    let x = 5;
     println!("x = {}", x);
 
-    let mut y = 10; // Mutable variable
+    // Use 'mut' keyword when you need to change a variable's value
+    // Only use mutable variables when necessary
+    let mut y = 10;
     println!("y before mutation = {}", y);
     y = 15;
     println!("y after mutation = {}", y);
 }
book-compendium/chapter-2/control_flow.rs (1)

1-13: Add educational comments and expand examples

While the code is correct, consider enhancing its educational value:

  1. Add explanatory comments for each control flow construct
  2. Use inclusive range syntax 0..=4 instead of 0..5 to demonstrate Rust's range operators
  3. Consider adding more control flow examples like:
    • while loops
    • match expressions
    • loop with break and continue

Here's a suggested enhancement:

+// Example of basic control flow in Rust
 fn main() {
+    // If-else demonstration
     let number = 7;
 
     if number < 10 {
         println!("Number is less than 10");
     } else {
         println!("Number is greater than or equal to 10");
     }
 
+    // For loop demonstration with inclusive range
-    for i in 0..5 {
+    for i in 0..=4 {
         println!("Value of i: {}", i);
     }
+
+    // While loop demonstration
+    let mut count = 0;
+    while count < 3 {
+        println!("Count: {}", count);
+        count += 1;
+    }
+
+    // Match expression demonstration
+    match number {
+        0 => println!("Zero"),
+        1..=9 => println!("Single digit"),
+        _ => println!("Multiple digits"),
+    }
 }
book-compendium/chapter-2/ownership.rs (1)

1-12: Expand ownership examples for better learning

While the code correctly demonstrates ownership transfer, consider adding more comprehensive examples to better illustrate Rust's ownership concepts:

  1. Add examples of borrowing with & and &mut
  2. Demonstrate ownership return patterns
  3. Show difference between Copy and Move types

Here's a suggested enhancement:

 fn main() {
+    // Ownership transfer example
     let s = String::from("Hello, Ownership!");
     take_ownership(s);
-    // Uncommenting the line below will cause an error, as `s` is no longer valid.
-    // println!("{}", s);
+    // println!("{}", s);  // Error: value borrowed here after move
+
+    // Borrowing example
+    let s2 = String::from("Hello, Borrowing!");
+    borrow_string(&s2);    // Passing reference instead of ownership
+    println!("Can still use s2: {}", s2);  // Works fine
+
+    // Mutable borrowing
+    let mut s3 = String::from("Hello, ");
+    modify_string(&mut s3);
+    println!("Modified string: {}", s3);
+
+    // Copy type example
+    let x = 5;
+    makes_copy(x);
+    println!("Can still use x: {}", x);  // Works fine, i32 implements Copy
 }
 
 fn take_ownership(some_string: String) {
     println!("{}", some_string);
 }
+
+fn borrow_string(some_string: &String) {
+    println!("{}", some_string);
+}
+
+fn modify_string(some_string: &mut String) {
+    some_string.push_str("Mutable!");
+}
+
+fn makes_copy(some_integer: i32) {
+    println!("{}", some_integer);
+}
book-compendium/chapter-2/README.md (1)

1-7: Enhance README with more detailed content

While the structure is clear, consider enhancing the educational value:

  1. Add learning objectives at the start
  2. Include brief code snippets for each concept
  3. Add explanations of key concepts
  4. Link to Rust documentation for further reading

Here's a suggested enhancement:

 # Chapter 2: Exploring Rust Basics
 
-This chapter introduces key Rust concepts with simple examples.
+## Learning Objectives
+
+After completing this chapter, you will understand:
+- How Rust's variable system ensures memory safety
+- Basic control flow constructs in Rust
+- Rust's unique ownership system
+
+## Contents
+
+### 1. Variables (`variables.rs`)
+Demonstrates variables, immutability, and mutability in Rust.
+
+```rust
+let x = 5;      // immutable by default
+let mut y = 1;  // mutable variable
+y += 1;         // can modify mutable variables
+```
+
+### 2. Control Flow (`control_flow.rs`)
+Explains basic control flow constructs like `if-else` and loops.
+
+```rust
+// Example if-else
+if number < 10 {
+    println!("Less than 10");
+}
+
+// Example for loop
+for i in 0..5 {
+    println!("Value: {}", i);
+}
+```
+
+### 3. Ownership (`ownership.rs`)
+Introduces Rust's ownership model and function interactions.
+
+```rust
+let s = String::from("hello");
+takes_ownership(s);  // ownership transferred
+// s is no longer valid here
+```
+
+## Further Reading
+- [Rust Book: Variables and Mutability](https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html)
+- [Rust Book: Control Flow](https://doc.rust-lang.org/book/ch03-05-control-flow.html)
+- [Rust Book: Understanding Ownership](https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html)
🧰 Tools
🪛 LanguageTool

[uncategorized] ~5-~5: Loose punctuation mark.
Context: ... simple examples. 1. variables.rs: Demonstrates variables, immutability, a...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~6-~6: Loose punctuation mark.
Context: ...bility in Rust. 2. control_flow.rs: Explains basic control flow constructs ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~7-~7: Loose punctuation mark.
Context: ...f-else and loops. 3. **ownership.rs`**: Introduces Rust's ownership model and f...

(UNLIKELY_OPENING_PUNCTUATION)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ad11fbd and 71529b4.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (4)
  • book-compendium/chapter-2/README.md (1 hunks)
  • book-compendium/chapter-2/control_flow.rs (1 hunks)
  • book-compendium/chapter-2/ownership.rs (1 hunks)
  • book-compendium/chapter-2/varibles.rs (1 hunks)
🧰 Additional context used
🪛 LanguageTool
book-compendium/chapter-2/README.md

[uncategorized] ~5-~5: Loose punctuation mark.
Context: ... simple examples. 1. variables.rs: Demonstrates variables, immutability, a...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~6-~6: Loose punctuation mark.
Context: ...bility in Rust. 2. control_flow.rs: Explains basic control flow constructs ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~7-~7: Loose punctuation mark.
Context: ...f-else and loops. 3. **ownership.rs`**: Introduces Rust's ownership model and f...

(UNLIKELY_OPENING_PUNCTUATION)

🔇 Additional comments (1)
book-compendium/chapter-2/varibles.rs (1)

2-3: Good demonstration of variable behavior

The code effectively shows the contrast between immutable and mutable variables through clear examples and appropriate print statements. The progression from immutable to mutable variables helps learners understand the concepts step by step.

Also applies to: 5-8

book-compendium/chapter-2/varibles.rs Outdated Show resolved Hide resolved
@SniperXyZ011
Copy link
Author

Fixed the typo

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
book-compendium/chapter-2/varible.rs (2)

2-4: Enhance the immutable variable example with type annotation

While the current example is correct, it could be more educational by explicitly showing type annotation.

-    let x = 5; // Immutable variable
+    let x: i32 = 5; // Immutable variable (32-bit integer)
     println!("x = {}", x);

5-9: Add explanatory comments about mutability

Consider adding more detailed comments to explain the concept of mutability for educational purposes.

-    let mut y = 10; // Mutable variable
+    // The 'mut' keyword allows us to change the value of y later
+    let mut y = 10;
     println!("y before mutation = {}", y);
     y = 15;
     println!("y after mutation = {}", y);
book-compendium/chapter-2/README.md (1)

1-4: Enhance the chapter introduction

The introduction could be more detailed to better set expectations for learners.

 # Chapter 2: Exploring Rust Basics
 
-This chapter introduces key Rust concepts with simple examples.
+This chapter introduces fundamental Rust programming concepts through practical examples. Each example is designed to demonstrate a specific aspect of the language, helping you build a strong foundation in Rust programming.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 71529b4 and 0608221.

📒 Files selected for processing (2)
  • book-compendium/chapter-2/README.md (1 hunks)
  • book-compendium/chapter-2/varible.rs (1 hunks)
🧰 Additional context used
🪛 LanguageTool
book-compendium/chapter-2/README.md

[uncategorized] ~5-~5: Loose punctuation mark.
Context: ...h simple examples. 1. variable.rs: Demonstrates variables, immutability, a...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~6-~6: Loose punctuation mark.
Context: ...bility in Rust. 2. control_flow.rs: Explains basic control flow constructs ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~7-~7: Loose punctuation mark.
Context: ...f-else and loops. 3. **ownership.rs`**: Introduces Rust's ownership model and f...

(UNLIKELY_OPENING_PUNCTUATION)

Comment on lines +1 to +9
fn main() {
let x = 5; // Immutable variable
println!("x = {}", x);

let mut y = 10; // Mutable variable
println!("y before mutation = {}", y);
y = 15;
println!("y after mutation = {}", y);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix the filename typo: "varible.rs" → "variable.rs"

The filename contains a typo which should be corrected to maintain consistency with the README and ensure clarity for learners.

Comment on lines +5 to +7
1. **`variable.rs`**: Demonstrates variables, immutability, and mutability in Rust.
2. **`control_flow.rs`**: Explains basic control flow constructs like `if-else` and loops.
3. **`ownership.rs`**: Introduces Rust's ownership model and function interactions.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

Update filename reference and add more details about each example

The README references "variable.rs" but the actual file is "varible.rs" (which should be fixed). Also, consider adding more details about what each example demonstrates.

-1. **`variable.rs`**: Demonstrates variables, immutability, and mutability in Rust.
-2. **`control_flow.rs`**: Explains basic control flow constructs like `if-else` and loops.
-3. **`ownership.rs`**: Introduces Rust's ownership model and function interactions.
+1. **`variable.rs`**: Demonstrates variables in Rust, covering:
+   - Immutable variables (default in Rust)
+   - Mutable variables using the `mut` keyword
+   - Type inference and explicit type annotations
+
+2. **`control_flow.rs`**: Explains basic control flow constructs including:
+   - Conditional statements (`if`-`else`)
+   - Different types of loops
+   - Early return and break statements
+
+3. **`ownership.rs`**: Introduces Rust's unique ownership system:
+   - Understanding ownership rules
+   - Move semantics
+   - Function parameter ownership

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~5-~5: Loose punctuation mark.
Context: ...h simple examples. 1. variable.rs: Demonstrates variables, immutability, a...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~6-~6: Loose punctuation mark.
Context: ...bility in Rust. 2. control_flow.rs: Explains basic control flow constructs ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~7-~7: Loose punctuation mark.
Context: ...f-else and loops. 3. **ownership.rs`**: Introduces Rust's ownership model and f...

(UNLIKELY_OPENING_PUNCTUATION)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant