May 2019
Intermediate to advanced
698 pages
17h 21m
English
The std::collections::LinkedList employs several unsafe methods in order to avoid the Rc<RefCell<Node<T>>> and next.as_ref().unwrap().borrow() calls that we saw when implementing a doubly linked list in a safe way. This also means that adding a node at either end entails the use of unsafe to set these pointers.
In this case, the code is easy to read and comprehend, which is important to avoid sudden crashes due to unsound code being executed. This is the core function to add a node in the front, shown as follows:
fn push_front_node(&mut self, mut node: Box<Node<T>>) { unsafe { node.next = self.head; node.prev = None; let node = Some(Box::into_raw_non_null(node)); match self.head { None => self.tail = node, Some(mut head) => head.as_mut().prev ...Read now
Unlock full access