Chapter 3 of 8

Data Structures and Collections

Data Structures and Collections

In this chapter of "Rust from beginner to advanced", we will explore the fundamental data structures and collections in Rust. Understanding these concepts is crucial for any Rust developer, as they form the basis of most programming tasks.

Key Concepts

  • Vectors: A growable array type that can store elements of any type.

  • Linked Lists: A dynamic collection of elements, where each element points to the next.

  • Hash Maps: A data structure that stores key-value pairs, allowing for efficient lookup and insertion.

Practical Examples

Let's take a look at how to use these data structures in Rust:

// Creating a vector
let numbers = vec![1, 2, 3, 4, 5];

// Creating a hash map
let mut person = std::collections::HashMap::new();
person.insert("name", "John");
person.insert("age", 30);

// Accessing elements in a vector
println!("{}", numbers[0]); // prints 1

// Accessing values in a hash map
println!("{}", person["name"]); // prints John

In this example, we create a vector numbers and a hash map person. We then access elements in the vector using indexing and values in the hash map using the key.

Best Practices

When working with data structures and collections in Rust, keep in mind:

  • Use Vec for dynamic arrays and HashMap for key-value pairs.

  • Avoid using raw pointers and instead opt for smart pointers like Box and Rc.

  • Always handle errors and edge cases when working with collections.

PreviousControl Flow and Functions