Rust Tutorial
Estimated reading: 4 minutes 30 views

🗂️ Rust Data Structures – Arrays, Vectors, Tuples, HashMaps, Structs & Enums

🧲 Introduction – Why Data Structures Matter in Rust

Rust’s memory safety and type system shine when organizing and managing collections of data. Whether you’re storing simple values in arrays or modeling complex types with structs and enums, Rust ensures zero-cost abstraction with compile-time guarantees.

🎯 In this guide, you’ll learn:

  • Key data structures in Rust and how to use them
  • Differences between fixed-size and growable containers
  • How to define custom types using structs and enums
  • Safe access, iteration, and manipulation techniques

📘 Topics Covered

🧱 Topic📖 Description
🧾 Data Structures OverviewSummary of built-in data containers in Rust
📏 ArraysFixed-size collections of elements with the same type
📦 VectorsGrowable versions of arrays using the Vec<T> type
🔗 TuplesGroup values of different types into a single compound value
🧭 HashMapsKey-value store using hashing, like dictionaries in other langs
🧱 StructsCustom types grouping named fields
🧩 EnumsTagged unions for variant-based logic and pattern matching

🧾 Rust – Data Structures Overview

Rust offers statically typed, memory-safe data structures:

  • 🔢 Arrays & Vectors for sequences
  • 📦 Tuples for mixed-type groups
  • 🔐 HashMaps for lookups
  • 🧱 Structs and 🧩 Enums for custom modeling

Each has its own performance and safety characteristics.


📏 Rust – Arrays

fn main() {
    let nums: [i32; 3] = [10, 20, 30];
    println!("First: {}", nums[0]);
}

🧠 Notes:

  • Fixed length known at compile time.
  • Indexing starts at 0.
  • Types and size must be specified ([i32; 3]).

Loop through an array:

for num in nums.iter() {
    println!("{}", num);
}

📦 Rust – Vectors (Vec<T>)

fn main() {
    let mut numbers = vec![1, 2, 3];
    numbers.push(4);
    println!("{:?}", numbers);
}

✅ Vectors are:

  • Dynamic: can grow or shrink
  • Stored on the heap
  • Accessed with indexing or .get(index)

Access safely:

match numbers.get(2) {
    Some(value) => println!("Found: {}", value),
    None => println!("Index out of bounds"),
}

🔗 Rust – Tuples

fn main() {
    let person: (&str, i32) = ("Alice", 30);
    println!("{} is {} years old", person.0, person.1);
}

💡 Tuples:

  • Hold multiple types.
  • Fixed size and order.
  • Use .0, .1, … for access.

Destructuring:

let (name, age) = person;

🧭 Rust – HashMap

use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("Alice", 90);
    scores.insert("Bob", 85);
    
    if let Some(score) = scores.get("Alice") {
        println!("Alice's score: {}", score);
    }
}

🧠 HashMap Tips:

  • Key and value types can differ.
  • Handle absence with Option.
  • Iteration:
for (name, score) in &scores {
    println!("{}: {}", name, score);
}

🧱 Rust – Structs

struct User {
    name: String,
    age: u8,
}

fn main() {
    let user1 = User {
        name: String::from("Dave"),
        age: 28,
    };
    println!("{} is {} years old", user1.name, user1.age);
}

✅ Structs:

  • Group related fields.
  • Enable code organization and reusability.

With impl:

impl User {
    fn greet(&self) {
        println!("Hello, {}!", self.name);
    }
}

🧩 Rust – Enums

enum Status {
    Active,
    Inactive,
    Pending,
}

fn main() {
    let user_status = Status::Active;

    match user_status {
        Status::Active => println!("User is active"),
        Status::Inactive => println!("User is inactive"),
        Status::Pending => println!("User is pending"),
    }
}

🧠 Enums:

  • Hold one variant at a time.
  • Can carry data:
enum Result<T, E> {
    Ok(T),
    Err(E),
}

📌 Summary – Recap & Next Steps

Rust’s data structures give you tools for every use case, from simple fixed-size arrays to complex user-defined types. With safety checks, explicit typing, and pattern matching, Rust ensures that your data handling is both fast and correct.

🔍 Key Takeaways:

  • Arrays and Tuples are fixed-size; Vectors are growable.
  • Structs and Enums help model custom logic.
  • HashMaps store key-value pairs and need importing.
  • Use .get(), pattern matching, and iterators for safe access.

⚙️ Real-World Use Cases:

  • Storing configuration options (HashMap)
  • Modeling APIs or states (Structs & Enums)
  • Managing dynamic lists of data (Vec)

❓ Frequently Asked Questions

What’s the difference between arrays and vectors in Rust?
✅ Arrays have fixed length; Vectors (Vec<T>) are growable and stored on the heap.


Can a tuple hold multiple data types in Rust?
✅ Yes. Tuples allow different types in one structure:

let info = ("Rust", 2025, true);

How do you iterate safely over a vector?
✅ Use .get() to avoid panics:

if let Some(val) = vec.get(1) {
    println!("{}", val);
}

When should I use a struct vs enum?
✅ Use struct for fixed fields (data), and enum for choices or variants (behavior/state).


Do I need to import HashMap?
✅ Yes. From Rust’s standard library:

use std::collections::HashMap;

Share Now :

Leave a Reply

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

Share

Rust Data Structures

Or Copy Link

CONTENTS
Scroll to Top