So I have been learning about and writing Rust code for a short while now. I really liked the idea of guaranteed safety, and also was interested in this new idea of ownership and lifetimes etc. Just like pure functional programming forces you to think about computing differently (if you are coming from an imperative background), Rust's ownership system forces a kind of mental shift. When I first encountered the concept of unsafe code in the Rust book, my reaction was something like "this looks like a cop out and I shall try to never use it".
But then for my first semi serious project, I wanted to employ an ECS design pattern, and ended up using Legion as the backbone. I soon encountered requirements that couldn't be catered for (using Legion) without upsetting the borrow checker, and the advice from the author is to make use of unchecked/unsafe facilities. Is this a common feature of API design in Rust?
As I Rust beginner, I'd like some help building an informed opinion APIs that expose unsafe functions. It's one thing to have unsafe internal code, but this is about unsafe code exposed in the API of the library.
From my current perspective, given my limited knowledge right now, it seems like there are 2 competing thoughts battling it out in my head:
- Library designers should always be able to write performant safe code with useful abstractions that cater for all intended use cases. Any unsafe function that is used to overcome the restrictions imposed by the borrow checker should be considered a design failure.
- There will always be some requirements that cannot be satisfied in a performant and safe way. Exposing unsafe functions in the API is the only way to enable users to satisfy these requirements whilst maintaining good performance.
I suppose a 3rd possibility is that right now unsafe code is more common than it theoretically needs to be given the current state of the compiler. I see that major enhancements to the compiler are still ongoing. Maybe one day, the language will evolve to the point that unsafe code will be deprecated?
I am a Rust beginner, trying to generate an informed option on this. Any advice/comments are welcome.