As a new comer to any language, I try to implement my own versions of basic data structures. Trees, vectors, linked-lists, etc. Then, after beating my head against a wall enough, I accept my inferiority and see how the language gurus do it. Sometimes the answer is that I just didn’t know about a feature. Other times it’s because there is a much more idiomatic way of doing the same thing (e.g. Writing an array structure in Haskell, for example, instead of using the basic cons list).
When I tried to write my own vector type structure, I ultimately failed. I’d ask other Rust developers how to allocate slices or make mutable copies of immutable slices. In the end, they’d end up saying things like, “Are you trying to avoid using Vec for some reason?”
So, I decided to jump into the Vec source code. Here it is for convenience:
Vec, as you can see, uses unsafe memory manipulation. Making the assumption that the language authors intended to do it this way and this isn’t just crusty Rust 0.1 code (correct me if I’m wrong, please), it raises a very important question for me:
Why is it impossible for a fundamental data structure to be implemented safely, when one of the core claims of the language is that it is fundamentally safe? Am I to walk away with the lesson that it’s appropriate and idiomatic to Rust to develop unsafe code when building data structures?
To me, this would be analogous to someone saying Linux is secure because all the controls on the system calls are really tightly locked down, but then finding out that
cat needs a special kernel driver to work properly.
Can someone help set me straight here? What am I missing?