How to make this implementation of a max binary heap more robust?

Hi all,

I'm learning Rust by implementing simple algorithms and data structures.
I wrote a max binary heap. You can find the code with some tests on GitHub here or if you prefer, on this playground.

I see that there is still a lot of calls to unwrap() so if I call pop() too many times, the code panics.

Any input on how to improve the code, especially when it comes to robustness, is welcome :pray:


Only addressing this part, you can have pop return an Option instead to remove the unwrap from the library (callers will have to handle the None case, via unwrap or something else, themselves):

        pub fn pop(&mut self) -> Option<T> {
            match {
                0 => None,
                _ => {
                    let deleted_node =;

( heap_is_generic_over_some_type_t also needs adjusted to deal with the changed return type.)

By using Vec::swap_remove, your only clone() is also avoided and the Clone bound on impl<T> MaxHeap<T> can be removed.

1 Like

Thanks @quinedot !

I implemented your feedback into the code. The swap_remove method is really handy.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.