pub struct AnyStack(/* private fields */);Expand description
A stack that can hold arbitrary types.
§Example
use rust_dsa::AnyStack;
// First, we create a new stack.
let mut stack = AnyStack::new();
// We can push elements of different types.
stack.push(4);
stack.push(true);
stack.push('a');
stack.push("str");
// We can check the top type.
assert!(stack.top_is::<&str>());
assert!(!stack.top_is::<char>());
// We can peek the top value.
assert_eq!(stack.peek::<&str>(), Some(&"str"));
// If we try to peek the wrong type, we get None.
assert_eq!(stack.peek::<bool>(), None);
// We can also pop values.
assert_eq!(stack.pop::<&str>(), Some("str"));
assert_eq!(stack.pop::<char>(), Some('a'));
// We can check the stack's length.
assert_eq!(stack.len(), 2);
// And clear the stack.
stack.clear();
assert!(stack.is_empty());Implementations§
Source§impl AnyStack
impl AnyStack
Sourcepub fn push<T: Any>(&mut self, value: T)
pub fn push<T: Any>(&mut self, value: T)
Pushes a value onto the stack.
§Example
use rust_dsa::AnyStack;
let mut stack = AnyStack::new();
stack.push(5);
assert_eq!(stack.pop::<i32>(), Some(5));
assert_eq!(stack.pop::<i32>(), None);Sourcepub fn pop<T: Any>(&mut self) -> Option<T>
pub fn pop<T: Any>(&mut self) -> Option<T>
Tries to pop a value of type T from the stack.
§Example
use rust_dsa::AnyStack;
let mut stack = AnyStack::new();
stack.push('a');
assert_eq!(stack.pop::<i32>(), None);
assert_eq!(stack.pop::<char>(), Some('a'));
assert_eq!(stack.pop::<char>(), None);Sourcepub fn peek<T: Any>(&self) -> Option<&T>
pub fn peek<T: Any>(&self) -> Option<&T>
Tries to peek a value of type T from the top of the stack.
§Example
use rust_dsa::AnyStack;
let mut stack = AnyStack::new();
stack.push(4);
assert_eq!(stack.peek::<i32>(), Some(&4));
assert_eq!(stack.peek::<char>(), None);Sourcepub fn top_is<T: Any>(&self) -> bool
pub fn top_is<T: Any>(&self) -> bool
Returns true if the top of the stack has type T.
This function returns false if the stack is empty.
§Example
use rust_dsa::AnyStack;
let mut stack = AnyStack::new();
stack.push('z');
assert!(stack.top_is::<char>());
assert!(!stack.top_is::<i32>());Trait Implementations§
Auto Trait Implementations§
impl Freeze for AnyStack
impl !RefUnwindSafe for AnyStack
impl !Send for AnyStack
impl !Sync for AnyStack
impl Unpin for AnyStack
impl !UnwindSafe for AnyStack
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more