...
Building A Rest Api With Rust And Axum Framework

Week 2: Rust Data Structures, Error Handling, and More

Week 2: Rust Data Structures, Error Handling, and More (Days 8–14)

In Week 2 of your Rust learning journey, we will dive deeper into important topics like Rust’s data structures, error handling, and more advanced concepts. By the end of this week, you’ll be equipped with essential skills to write more efficient, reliable, and robust Rust code.


Day 8: Vectors in Rust

  • Understanding Vectors: Vectors are dynamic arrays that can grow or shrink in size. Learn how to declare and use vectors in Rust. Unlike arrays, vectors are heap-allocated, and you can modify their size dynamically. Example:
  fn main() {
      let mut numbers = vec![1, 2, 3];
      numbers.push(4);
      println!("{:?}", numbers);
  }
  • Operations on Vectors: Learn how to manipulate vectors (adding elements, removing elements, iterating through them, etc.). Example:
  let mut numbers = vec![1, 2, 3, 4];
  numbers.pop(); // Removes the last element
  for num in numbers.iter() {
      println!("{}", num);
  }

Day 9: Hash Maps

  • Introduction to Hash Maps: Hash maps are collections that store key-value pairs. Rust’s HashMap allows you to store and retrieve data quickly based on a key. Example:
  use std::collections::HashMap;

  fn main() {
      let mut map = HashMap::new();
      map.insert("name", "Rust");
      map.insert("age", "5");

      println!("{:?}", map);
  }
  • Working with Hash Maps: Learn to add, update, retrieve, and remove elements from a HashMap. Use common methods like get(), insert(), remove(), and contains_key(). Example:
  let name = map.get("name").unwrap();
  println!("Name: {}", name);

Day 10: Option Type

  • What is Option in Rust? The Option type is used for scenarios where a value might be present or absent. It’s an enum that can either be Some(T) or None. Example:
  fn find_number(numbers: Vec<i32>, target: i32) -> Option<i32> {
      for &num in numbers.iter() {
          if num == target {
              return Some(num);
          }
      }
      None
  }
  • Working with Option: Learn how to handle Option values safely using methods like unwrap(), map(), and_then(), and pattern matching.

Day 11: Result Type

  • What is Result in Rust? The Result type is used for error handling. It’s an enum with two variants: Ok(T) for success and Err(E) for failure. Example:
  fn divide(x: i32, y: i32) -> Result<i32, String> {
      if y == 0 {
          Err("Cannot divide by zero".to_string())
      } else {
          Ok(x / y)
      }
  }
  • Error Handling with Result: Learn how to use match to handle both Ok and Err cases. Example:
  match divide(10, 2) {
      Ok(result) => println!("Result: {}", result),
      Err(e) => println!("Error: {}", e),
  }

Day 12: Structs and Enums

  • Structs in Rust: Structs are custom data types that allow you to group related data. Learn how to define and instantiate structs in Rust. Example:
  struct Person {
      name: String,
      age: u32,
  }

  fn main() {
      let person = Person {
          name: String::from("Alice"),
          age: 30,
      };
      println!("Name: {}, Age: {}", person.name, person.age);
  }
  • Enums in Rust: Enums allow you to define a type that can be one of several variants. Learn how to define and use enums. Example:
  enum Direction {
      Up,
      Down,
      Left,
      Right,
  }

  fn main() {
      let move_dir = Direction::Up;
      match move_dir {
          Direction::Up => println!("Moving Up"),
          Direction::Down => println!("Moving Down"),
          _ => println!("Other direction"),
      }
  }

Day 13: Pattern Matching

  • Pattern Matching in Rust: Rust’s match statement is a powerful tool for handling various cases. Learn how to use match to handle enums, structs, and even other data types like integers and strings. Example:
  enum TrafficLight {
      Red,
      Yellow,
      Green,
  }

  fn get_light_message(light: TrafficLight) -> String {
      match light {
          TrafficLight::Red => String::from("Stop"),
          TrafficLight::Yellow => String::from("Get ready"),
          TrafficLight::Green => String::from("Go"),
      }
  }

Day 14: Ownership and Borrowing

  • Ownership in Rust: Rust’s ownership system ensures memory safety. A value in Rust can only have one owner, and when the owner goes out of scope, the value is automatically cleaned up.
  • Borrowing in Rust: Borrowing allows you to reference data without taking ownership. Learn how borrowing works through references (&) and mutable references (&mut). Example:
  fn main() {
      let s1 = String::from("hello");
      let s2 = &s1; // Immutable borrow

      println!("s1 = {}, s2 = {}", s1, s2);
  }
  • Learn about mutable borrowing and dangling references.

Conclusion

In Week 2, you’ve covered essential Rust topics like data structures, error handling, and pattern matching. These concepts are foundational for writing efficient and safe Rust code. By now, you should be comfortable with handling vectors, hash maps, and managing errors using the Option and Result types. These skills will serve as a base for more advanced Rust topics in the upcoming weeks.

Next Week: Advanced Rust Concepts and Concurrency

In Week 3, you’ll dive into more advanced topics, such as concurrency with goroutines and channels, and explore Rust’s standard library. Keep practicing and refining your skills!

Leave a Reply

Your email address will not be published. Required fields are marked *