Chapter 1: A Taste of Rust
* Introduces Rust's basics: type safety, ownership, and borrowing.
* Example: Declaring a mutable integer: `let mut age = 10;`
Chapter 2: Control Flow and Functions
* Covers conditional statements, loops, and function definitions.
* Example: A function that calculates the greatest common divisor:
```
fn gcd(a: u128, b: u128) -> u128 {
if b == 0 {
a
} else {
gcd(b, a % b)
}
}
```
Chapter 3: Ownership and Mutability
* Explains how Rust's ownership system ensures memory safety.
* Example: A vector that owns its data: `let mut numbers = vec![1, 2, 3];`
Chapter 4: Structs and Enums
* Covers defining custom data types and working with different variants.
* Example: A `Person` struct with name and age fields:
```
struct Person {
name: String,
age: u8,
}
```
Chapter 5: Smart Pointers
* Introduces reference-counted and immutable pointers for managing memory.
* Example: Using a `Rc` to share a `Person` object between multiple owners:
```
let person = Rc::new(Person { name: "Alice".to_string(), age: 25 });
```
Chapter 6: Trait Objects
* Explains how to work with objects that implement specific traits.
* Example: A function that takes any object that implements the `Display` trait:
```
fn print_anything(x: T) {
println!("{}", x);
}
```
Chapter 7: Error Handling
* Covers Rust's advanced error handling mechanisms using `Result` and `Option`.
* Example: A function that returns an error if a file cannot be opened:
```
fn open_file(path: &str) -> Result {
File::open(path)
}
```
Chapter 8: Async Programming
* Introduces async programming in Rust using the `futures` and `tokio` libraries.
* Example: A function that fetches a URL asynchronously:
```
async fn fetch_url(url: &str) -> Result {
let resp = reqwest::get(url).await?;
let body = resp.text().await?;
Ok(body)
}
```