Rust Example for Array and Dyamic Element Management (aka Vector-based Element Management)

CK CK 3788 
Created at
Updated at  
625 0 0

Rust arrays are fixed-size collections of elements of the same type. Operations include accessing elements by index (using bracket notation like array[index]), iterating over elements using loops or iterators, and performing calculations using methods like len() (to get the length) or comparing arrays for equality. However, unlike dynamically sized collections like vectors, you cannot directly add or remove elements from a Rust array after its creation; its size is determined at compile time. You can create new arrays by copying or slicing existing ones.

Here's a simple example demonstrating how to work with arrays in Rust:

fn main() {
    // Defining an array with 5 integers
    let numbers: [i32; 5] = [10, 20, 30, 40, 50];

    // Accessing array elements
    println!("First number: {}", numbers[0]);
    println!("Second number: {}", numbers[1]);

    // Iterating through the array
    println!("Iterating through the array:");
    for number in numbers.iter() {
        println!("{}", number);
    }

    // Using array with a fixed value
    let repeated_values: [i32; 3] = [42; 3]; // [42, 42, 42]
    println!("Array with repeated values: {:?}", repeated_values);

    // Checking the length of the array
    println!("Length of numbers array: {}", numbers.len());
}

Explanation:

  1. Array Declaration:
    • let numbers: [i32; 5] = [10, 20, 30, 40, 50];
      Declares an array of type i32 with 5 elements.
    • The size of an array is fixed and must be known at compile time.
  2. Accessing Elements:
    • Use square brackets to access elements, e.g., numbers[0].
  3. Iteration:
    • Use .iter() to get an iterator over the array.
  4. Repeated Values:
    • [value; size] initializes an array where all elements are value.
  5. Length:
    • Use .len() to get the size of the array.

Output:

First number: 10
Second number: 20
Iterating through the array:
10
20
30
40
50
Array with repeated values: [42, 42, 42]
Length of numbers array: 5

In Rust, arrays have a fixed size determined at compile time, so you cannot dynamically add or remove elements from them. However, you can use a vector (Vec<T>), which is a dynamically-sized collection type in Rust, for such operations.

Example: Using a Vector for Dynamic Growth

fn main() {
    // Create an empty vector
    let mut numbers: Vec<i32> = Vec::new();

    // Adding elements to the vector
    numbers.push(10);
    numbers.push(20);
    numbers.push(30);

    // Display the vector
    println!("Vector: {:?}", numbers);

    // Remove the last element
    numbers.pop();
    println!("After pop: {:?}", numbers);

    // Accessing elements
    println!("First element: {}", numbers[0]);

    // Iterating through the vector
    println!("Iterating through the vector:");
    for number in &numbers {
        println!("{}", number);
    }

    // Get the length
    println!("Vector length: {}", numbers.len());
}

Explanation:

  1. Create a Vector:
    • Vec::new() creates an empty vector.
    • Alternatively, you can initialize with values: let numbers = vec![10, 20, 30];.
  2. Add Elements:
    • numbers.push(value); appends value to the end of the vector.
  3. Remove Elements:
    • numbers.pop(); removes the last element and returns it as an Option.
  4. Accessing Elements:
    • Use numbers[index] for direct access or .get(index) for safe access (returns an Option).
  5. Dynamic Size:
    • Vectors grow and shrink as needed.

Output:

Vector: [10, 20, 30]
After pop: [10, 20]
First element: 10
Iterating through the vector:
10
20
Vector length: 2

Use vectors when you need dynamic resizing. Arrays are more efficient for fixed-size collections.

Tags Dynamically Sized Collections Rust Array Declaration Rust Array Elements Rust Arrays Rust Vectors Facebook X
Comments 0
Similar posts
  1. Rust array is fixed size. Can I modify its content?
    587
  2. How do I implement a stack in Rust?
    771
  3. Arrays and Slices in Rust
    341
  1. How do I implement a heap in Rust?
    685
  2. Rust-GPU-tools for interacting with various GPU APIs
    757
  3. The || syntax in Rust - also known as a closure
    602
  4. Basic Rust Thread Example to Perform Concurrent Computation
    619
  5. Multi-threaded HLS Server in Rust
    774
  6. Run a specific module in a external file with Rust
    571
  7. Question(?) Operator in Rust
    573
  8. Rust code example to access MySQL
    1,100
  9. Rust Documentation
    316
  10. Rust Compatibility
    726
  11. Rust Unsafe Operations
    369
  12. Rust Testing
    1,246
  13. Rust Std misc
    375
  14. Rust Std library types
    370
  15. Rust Error Handling
    350
  16. Rust Macro Rules
    1,525
  17. Rust mechanism for defining shared behavior across different types - Traits
    1,774
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,256
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    105
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    108
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    209
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    154
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  15. What is RedisVL?
    117
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    599
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    269
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    355
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    231
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    229
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    204
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    264
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233