| 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. 
Here's a simple implementation of a stack in Rust: Stack Implementationpub 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- Generic Type
T: The stack is implemented as a generic type to hold any type of element. - 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 FeaturesVec 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. |