Table of content

Stack in Rust

A stack is a data structure with LIFO features for the last in, first out. Take the above picture borrowed from Wikipedia as an example. In the case of the fifth picture, if you want to get 2, you must first remove 3, 4, and 5 from the stack.

The bottom and top of the stack are abstract concepts. The top is where the data is added, removed, and the busier end and the bottom is the other end.

The space of the stack may be limited, that is, it is also possible to achieve an infinite stack of space. In view of the fact that stacking of limited spaces is more common, we choose to implement stacks with limited space.

There are two ways to implement stack stacking: array and linked list, here you choose to implement a vector like an array.

  • with_capacity : Define a stack with limited space.
  • push : Add new information to the data structure.
  • pop : Move the newly added data out of the data structure.
  • size : (optional) to get the size of the stack.
  • peek : (optional) peek at the last added data when the data is not stacked on the stack.
pub struct Stack<T> {
	maxsize: usize,
	items: Vec<T>,

impl<T> Stack<T> {

pub fn with_capacity(maxsize: usize) -> Self { Self { maxsize, items: Vec::with_capacity(maxsize), } } pub fn pop(&mut self) -> Option<T> { self.items.pop() } pub fn push(&mut self, item: T) -> bool { if self.items.len() == self.maxsize { return false; } self.items.push(item); return true; } pub fn size(&self) -> usize { self.items.len() } pub fn peek(&self) -> Option<&T> { self.items.last() } }


mod tests { #[test] fn test_new_with_capacity() { let stack = super::Stack::<u32>::with_capacity(10); assert_eq!(10, stack.items.capacity()); }

#[test] fn test_pop(){ let mut stack = super::Stack::<u32>::with_capacity(1); stack.push(1u32); assert_eq!(Some(1u32), stack.pop()); assert_eq!(None, stack.pop()); }

#[test] fn test_push() { let mut stack = super::Stack::<u32>::with_capacity(1); stack.push(32u32); assert_eq!(Some(&32u32), stack.peek()); assert_eq!(1, stack.size()); }

#[test] fn test_push_maxsize() { let mut stack = super::Stack::<u32>::with_capacity(1); assert_eq!(true, stack.push(1u32)); assert_eq!(Some(&1u32), stack.peek()); assert_eq!(false, stack.push(2u32)); }

#[test] fn test_size() { let mut stack = super::Stack::<u32>::with_capacity(1); assert_eq!(0, stack.size()); stack.push(1u32); assert_eq!(1, stack.size()); } }

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions