2 ms·
Can someone explain why raw_tail was necessary in the add_to_tail function?
by simplify 8y ago
Can someone explain why raw_tail was necessary in the add_to_tail function?
- codesections 8y agoWe needed to use a raw pointer there because of Rust's ownership system. Here's the short version: Rust wants everything to have exactly one owner and enforces that by disallowing multiple mutable references to the same data (or, for that matter, multiple references to the data if even one of the references is mutable). But that doesn't play too well with linked lists. You need to have a reference to the tail node from the previous node and have a reference from the list itself. And you need to be able to mutate the tail node, so you can't just do that with immutable references. Now, rust does have some safe ways to solve that type of problem (Arc and RefCells are two). But it turns out that the best way to solve it here is to make the jump to `unsafe` code since we can guarantee the invariants that keep it from being unsafe in practice.