Rust Data Structures
Estimated reading: 3 minutes 35 views

🦀 Rust – Data Structures (Overview): Build with Arrays, Tuples, Vectors, and More

🧲 Introduction – Why Learn Data Structures in Rust?

Data structures are building blocks of real applications. Whether you’re storing configuration, tracking game states, or parsing user input, Rust offers safe and performant data structures like arrays, vectors, tuples, hash maps, enums, and structs—all tightly integrated with the ownership model.

🎯 In this guide, you’ll learn:

  • Key built-in data structures in Rust
  • How each one is used and declared
  • Ownership behavior across data structures
  • Quick examples, outputs, and usage scenarios

🗂️ 1. Arrays – Fixed-size, Stack-allocated Lists

🔹 Code Example:

fn main() {
    let nums = [1, 2, 3, 4, 5];
    println!("First number: {}", nums[0]);
}

🧠 Highlights:

  • Fixed-length ([T; N])
  • Stored on stack
  • Indexing is bounds-checked (safe)

📤 Output:

First number: 1

📦 2. Vectors – Growable, Heap-allocated Lists

🔹 Code Example:

fn main() {
    let mut names = vec!["Alice", "Bob"];
    names.push("Charlie");
    println!("{:?}", names);
}

🧠 Highlights:

  • Use vec![] or Vec::new()
  • Stored on heap
  • Can grow and shrink dynamically

📤 Output:

["Alice", "Bob", "Charlie"]

🧊 3. Tuples – Grouping Heterogeneous Values

🔹 Code Example:

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

🧠 Highlights:

  • Fixed size
  • Elements can be different types
  • Indexed with .0, .1, etc.

📤 Output:

Alice is 30 years old.

🔢 4. Structs – Custom Data Types

🔹 Code Example:

struct Book {
    title: String,
    pages: u32,
}

fn main() {
    let b = Book {
        title: String::from("Rust Book"),
        pages: 300,
    };

    println!("{} has {} pages.", b.title, b.pages);
}

🧠 Highlights:

  • Define your own data types
  • Encapsulate related fields
  • Works with impl for methods

📤 Output:

Rust Book has 300 pages.

🔁 5. Enums – Tagged Unions for Variants

🔹 Code Example:

enum State {
    Loading,
    Loaded,
    Error(String),
}

fn main() {
    let status = State::Error(String::from("404"));

    match status {
        State::Loading => println!("Loading..."),
        State::Loaded => println!("Done!"),
        State::Error(msg) => println!("Error: {}", msg),
    }
}

🧠 Highlights:

  • Powerful with match
  • Can hold data variants
  • Core to Option, Result, etc.

📤 Output:

Error: 404

🗃️ 6. HashMap – Key-Value Store

🔹 Code Example:

use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("Alice", 50);
    scores.insert("Bob", 80);

    println!("{:?}", scores);
}

🧠 Highlights:

  • Use from std::collections
  • Key and value must implement Eq and Hash
  • Ownership of inserted values is moved

📤 Output (order may vary):

{"Alice": 50, "Bob": 80}

🔒 Ownership Rules Across Data Structures

Data StructureOwnership Behavior
ArrayOwns elements; values copied or moved
VectorOwns heap values; pushing moves values
TupleEach element has its own ownership
StructEach field is owned; clone() needed if reused
HashMapBoth key and value are moved in by default

📌 Summary – Recap & Next Steps

Rust’s built-in data structures are versatile, performant, and fully integrated with its memory safety guarantees. From low-level arrays to high-level hash maps, you can model everything while staying safe and expressive.

🔍 Key Takeaways:

  • Use arrays for fixed-size data, vectors for dynamic lists
  • tuples are ideal for grouped values, structs for named fields
  • enums model variants; hash maps manage key-value data
  • All data structures honor ownership and lifetime rules

⚙️ Next: Explore each structure in detail starting with Rust – Arrays.


❓FAQs


When should I use a vector instead of an array?
✅ Use a vector (Vec<T>) when the size is not known at compile-time or when it can change dynamically.


Can I mix types in a vector?
❌ No. Vectors require all elements to be of the same type. Use enums or boxed traits for mixed types.


Do data structures copy or move values?
✅ By default, they move values unless they implement the Copy trait. Use .clone() if duplication is needed.


How do I iterate over a tuple or struct?
✅ Use destructuring or indexing (.0, .1) for tuples. Use field names for structs.


Share Now :

Leave a Reply

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

Share

Rust – Data Structures (Overview)

Or Copy Link

CONTENTS
Scroll to Top