4 ms·
Yes, internals of data structures often need unsafe. At least with Cargo, and generics, you can implement them once, and then share them amongst projects. It's
by steveklabnik 10y ago
Yes, internals of data structures often need unsafe. At least with Cargo, and generics, you can implement them once, and then share them amongst projects. It's also why we have a fair number of data structures in the standard library; they will be audited a bit more heavily this way.
- bluejekyll 10y agounsafe in Rust == telling the compiler I know what I'm doing here, so eff off. Other languages do this too, for instance in Java you can override final with reflection. I lost my mind, both good and bad, when I discovered this.
- steveklabnik 10y agoBut only in a controlled way. Unsafe doesn't change the semantics of existing code, it only adds the ability to do a few extra things. So you're still going to get a lot of safety checks, even within an unsafe block. You still have to be careful, but it's not no-holds-barred.
- bluejekyll 10y agoYeah. I've read your chapter on this repeatedly, and then the Rustinomicon, both hugely useful, but so far all I've done is use of for Rust -> C bindings and vice versa. It's taken me a year to feel good about my Rust code, I'm still getting a handle on unsafe though.
- Const-me 10y agoEven using unsafe, are you sure I can implement e.g. efficient linked list data structure? By “efficient” I mean I want to split my list in two for O(1) complexity, like other programming languages do.
- frankmcsherry 10y agoHere is a version (https://is.gd/bFCpMq https://is.gd/bFCpMq) that might be instructive. It is based on a simple ref count cycle of structs like: pub struct ListNode<T> { data: T, prev: Weak<RefCell<ListNode<T>>>, next: Rc<RefCell<ListNode<T>>>, } The code linked above probably has bugs (for sure with singleton lists), but I hope you get the idea. It allows you to splice lists in and out in constant time. Also, the code doesn't use `unsafe`. Now, you would need to use `unsafe` somewhere to actually create a list, in order to initialize the fields (or you could change the type of `next` to be `Option<...>`). However, the use of `unsafe` would be limited to that method. This tries to get at the difference between (i) occasionally using `unsafe` and (ii) having no safety guarantees at all. There are probably lots of other pain points that you can bring up, and I'm not trying to say this should be good enough, but I thought it might help explain what is possible.
- steveklabnik 10y agoUsing unsafe, you can do anything C can do.