How do I implement a stack in Rust?

CK CK 3788 
Created at  
752 0 0

To implement a stack in Rust, you can use a Vec (vector) as the underlying storage since it provides dynamic array-like functionality and supports efficient operations for a stack.

How do I implement a stack in Rust?

Here's a simple implementation of a stack in Rust:

Stack Implementation

pub struct Stack<T> {
    elements: Vec<T>,
}

impl<T> Stack<T> {
    // Create a new stack
    pub fn new() -> Self {
        Stack {
            elements: Vec::new(),
        }
    }

    // Push an element onto the stack
    pub fn push(&mut self, item: T) {
        self.elements.push(item);
    }

    // Pop an element off the stack
    pub fn pop(&mut self) -> Option<T> {
        self.elements.pop()
    }

    // Peek at the top element without removing it
    pub fn peek(&self) -> Option<&T> {
        self.elements.last()
    }

    // Check if the stack is empty
    pub fn is_empty(&self) -> bool {
        self.elements.is_empty()
    }

    // Get the size of the stack
    pub fn size(&self) -> usize {
        self.elements.len()
    }
}

fn main() {
    let mut stack = Stack::new();

    // Push elements onto the stack
    stack.push(1);
    stack.push(2);
    stack.push(3);

    // Peek at the top element
    println!("Top element: {:?}", stack.peek());

    // Pop elements off the stack
    println!("Popped: {:?}", stack.pop());
    println!("Popped: {:?}", stack.pop());

    // Check if the stack is empty
    println!("Is stack empty? {}", stack.is_empty());

    // Check the size of the stack
    println!("Stack size: {}", stack.size());
}

Explanation

  1. Generic Type T: The stack is implemented as a generic type to hold any type of element.
  2. Operations:
    • push adds an element to the top of the stack.
    • pop removes and returns the top element, or None if the stack is empty.
    • peek provides a reference to the top element without removing it.
    • is_empty checks if the stack has no elements.
    • size returns the number of elements in the stack.

 

Key Features

  • Vec is used internally because it allows efficient appending and popping of elements from the end.
  • Rust’s ownership and borrowing rules ensure memory safety without garbage collection.

This implementation provides a basic, extensible stack. You can add additional functionality as needed for your specific use case.

Tags Rust Stack Rust Vectors Stack Facebook X
Comments 0
Similar posts
  1. Rust array is fixed size. Can I modify its content?
    580
  2. Rust Example for Array and Dyamic Element Management (aka Vector-based Element Management)
    619
  3. Rust Std library types
    367
  4. Stack Tutorial In C#
    665
  1. How do I implement a heap in Rust?
    672
  2. Rust-GPU-tools for interacting with various GPU APIs
    753
  3. Rust array is fixed size. Can I modify its content?
    580
  4. Rust Example for Array and Dyamic Element Management (aka Vector-based Element Management)
    619
  5. The || syntax in Rust - also known as a closure
    599
  6. Basic Rust Thread Example to Perform Concurrent Computation
    611
  7. Multi-threaded HLS Server in Rust
    759
  8. Run a specific module in a external file with Rust
    567
  9. Question(?) Operator in Rust
    565
  10. Rust code example to access MySQL
    1,096
  11. Rust Documentation
    309
  12. Rust Compatibility
    714
  13. Rust Unsafe Operations
    356
  14. Rust Testing
    1,230
  15. Rust Std misc
    367
  16. Rust Std library types
    367
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,733
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    86
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    198
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    234
  17. The Concept of Scaffolding in AI Agents
    222
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    576
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    253
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    328
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252