pub struct Stack<T> { /* private fields */ }Implementations§
Source§impl<T> Stack<T>
impl<T> Stack<T>
pub fn new() -> Self
pub fn push(&mut self, elem: T)
Sourcepub fn pop(&mut self) -> Result<T, &str>
pub fn pop(&mut self) -> Result<T, &str>
In pop function, we trying to:
- check if the list is empty, so we use enum Option
, it can either be Some(T) or None - if it’s empty, return None
- if it’s not empty
- remove the head of the list
- remove its elem
- replace the list’s head with its next
- return Some(elem), as the situation if need
so, we need to remove the head, and return the value of the head
pub fn is_empty(&self) -> bool
pub fn peek(&self) -> Option<&T>
pub fn peek_mut(&mut self) -> Option<&mut T>
pub fn into_iter_for_stack(self) -> IntoIter<T>
pub fn iter(&self) -> Iter<'_, T>
pub fn iter_mut(&mut self) -> IterMut<'_, T>
Trait Implementations§
Source§impl<T> Drop for Stack<T>
The drop method of singly linked list. There’s a question that do we need to worry about cleaning up our list?
As we all know the ownership and borrow mechanism, so we know the type will clean automatically after it goes out the scope,
this implement by the Rust compiler automatically did which mean add trait drop for the automatically.
impl<T> Drop for Stack<T>
The drop method of singly linked list. There’s a question that do we need to worry about cleaning up our list?
As we all know the ownership and borrow mechanism, so we know the type will clean automatically after it goes out the scope,
this implement by the Rust compiler automatically did which mean add trait drop for the automatically.
So, the complier will implements Drop for List->Link->Box<Node> ->Node automatically and tail recursive to clean the elements
one by one. And we know the recursive will stop at Box
As we know we can’t drop the contents of the Box after deallocating, so we need to manually write the iterative drop