Arrays and Slices in Rust

CK CK 3788 
Created at  
338 0 0

An array is a collection of objects of the same type T, stored in contiguous memory. Arrays are created using brackets [], and their length, which is known at compile time, is part of their type signature [T; length].

Slices are similar to arrays, but their length is not known at compile time. Instead, a slice is a two-word object; the first word is a pointer to the data, the second word is the length of the slice. The word size is the same as usize, determined by the processor architecture, e.g. 64 bits on an x86-64. Slices can be used to borrow a section of an array and have the type signature &[T].

use std::mem;

// This function borrows a slice.
fn analyze_slice(slice: &[i32]) {
    println!("First element of the slice: {}", slice[0]);
    println!("The slice has {} elements", slice.len());
}

fn main() {
    // Fixed-size array (type signature is superfluous).
    let xs: [i32; 5] = [1, 2, 3, 4, 5];

    // All elements can be initialized to the same value.
    let ys: [i32; 500] = [0; 500];

    // Indexing starts at 0.
    println!("First element of the array: {}", xs[0]);
    println!("Second element of the array: {}", xs[1]);

    // `len` returns the count of elements in the array.
    println!("Number of elements in array: {}", xs.len());

    // Arrays are stack allocated.
    println!("Array occupies {} bytes", mem::size_of_val(&xs));

    // Arrays can be automatically borrowed as slices.
    println!("Borrow the whole array as a slice.");
    analyze_slice(&xs);

    // Slices can point to a section of an array.
    // They are of the form [starting_index..ending_index].
    // `starting_index` is the first position in the slice.
    // `ending_index` is one more than the last position in the slice.
    println!("Borrow a section of the array as a slice.");
    analyze_slice(&ys[1 .. 4]);

    // Example of empty slice `&[]`:
    let empty_array: [u32; 0] = [];
    assert_eq!(&empty_array, &[]);
    assert_eq!(&empty_array, &[][..]); // Same but more verbose

    // Arrays can be safely accessed using `.get`, which returns an
    // `Option`. This can be matched as shown below, or used with
    // `.expect()` if you would like the program to exit with a nice
    // message instead of happily continue.
    for i in 0..xs.len() + 1 { // Oops, one element too far!
        match xs.get(i) {
            Some(xval) => println!("{}: {}", i, xval),
            None => println!("Slow down! {} is too far!", i),
        }
    }

    // Out of bound indexing on array causes compile time error.
    //println!("{}", xs[5]);
    // Out of bound indexing on slice causes runtime error.
    //println!("{}", xs[..][5]);
}
Tags Rust Rust Arrays Rust Data Types Rust Slices Facebook X
Comments 0
Similar posts
  1. Tuples in Rust - a collection of values of different types
    297
  2. Rust Custom Data Types - struct, enum, use, constants
    298
  3. Literals and operators in Rust
    296
  4. Rust Data Type - What is mutable?
    256
  5. Rust Code Testing Environment without installing anything on your computer
    324
  6. Rust Data Type Operations - Casting, Literals, Inference, Aliasing
    326
  7. Rust Thread Example
    346
  8. How do I setup Rust development environment?
    368
  9. Rust - System Programming Language invented by Graydon Hoare
    280
  10. Rust Example for Array and Dyamic Element Management (aka Vector-based Element Management)
    622
  11. Rust array is fixed size. Can I modify its content?
    583
  12. Why America's Biggest Tech Companies Are Betting on Rust?
    287
  1. Rust Error Handling
    342
  2. Rust Macro Rules
    1,508
  3. Rust mechanism for defining shared behavior across different types - Traits
    1,762
  4. Rust Scoping Rules - only accessible within the block of code
    1,066
  5. Rust Generics - Generalizing types and functionalities
    1,349
  6. Rust Attributes for conditional compilation, crate, lints, mark functions, macros
    313
  7. Rust Package Management Tool - cargo
    307
  8. Rust compilation unit - Crates
    251
  9. Rust Modules - Visivility, Struct Visibility, Use Declaration, super and self, File Hierarchy
    1,889
  10. Rust functions - Methods, Closures, Capturing
    1,198
  11. Rust Flow of Control - if/else, loop. while, for and range, match, if let, let-else, while let
    335
  12. Rust Expressions
    924
  13. Rust Conversion - From, Into, TryFrom, TryInto
    1,309
  14. gRPC library for Rust
    342
  15. Variable Bindings in Rust
    966
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    42
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    36
  3. How do I create animated background for Google Meet?
    21,018
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    251
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    515
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    288
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    232
  16. TPU & GPU Cluster Management Tools
    245
  17. The Concept of Scaffolding in AI Agents
    234
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    222
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    221
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    196
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    219
  30. Understanding Data Lineage
    263