4 ms·
Learning Rust by writing a linked list is like learning Python by writing a CPython extension. Sure, you'll learn a lot, and it may even be useful, but it's not
by pornel 7y ago
Learning Rust by writing a linked list is like learning Python by writing a CPython extension. Sure, you'll learn a lot, and it may even be useful, but it's not the typical experience of using the language.
I've seen people completely confused that such simple "CS 101" thing is such a mess in Rust. But nobody actually writes linked lists in Rust:
• The borrow checker wants to have clear single ownership, and doesn't support reference cycles. Lists happen to have mixed ownership. I'm not sure if it's even possible to prove at compile time that a list will never have a cycle, but it seems at least in the Sufficiently Smart Compiler territory.
• Safe linked lists are in the std lib if you really need them, but std has also plenty of other containers that are more efficient on modern hardware.
Compile-time safety checks can't prove all valid programs are valid (halting problem). Instead of going after the enormously complex problem, the borrow checker rules are actually pretty simple. It's a feature, not a defect. Simplifying the problem to single ownership with shared-immutable vs exclusive-mutable makes it much easier to reason about borrow checking. If something doesn't fit these rules, you either use a different approach, or use `unsafe`, and then wrap it in a higher-level safe abstraction that fits the model.
- slaymaker1907 7y agoAlso, the way destructors work make it such that most custom linked lists are prone to stack overflows unless they use unsafe.
- umanwizard 7y agoFor what it's worth, this is also true of C++, where the most "natural" way to write a linked list is `struct Node { unique_ptr<Node> next; }`
- Igelau 7y agoI think you missed the point. The guide is fairly upfront about it being a bad idea and a very atypical approach to learning Rust.
- peteretep 7y ago> But nobody actually writes linked lists in Rust It feels entirely like you didn't even start reading this. He spends a whole long first page bitching about Linked Lists and why nobody uses them in Rust.
- cormacrelf 7y agoI come back to this from time to time as a reference for doing the uglier things in Rust. Writing Iterator<Item=&T> with raw pointers, recursive drops, etc. It's better than reading the std source code, because it's got a guide right next the code. I think I'm using it as intended. The title might be suboptimal/confusing for what it's trying to do. It's less a resource for newcomers than an illustration of someone bumping their head against the wall to do hard things.