Unsafe Deref Trait

I often make newtypes around raw pointers, and enabling the same Deref functionality that exists with raw pointers and refernces would go a long way towards making these wrappers more ergonomic. Today though, there's really no way to do that in Rust, which means that newtypes over raw pointers are kind of gimped.

My proposal is basically to a copy-paste Deref and DerefMut, and make them unsafe traits that work on raw pointers.


For reference, here is a different proposal that partly addresses the same ergonomic problem: Need for -> operator for Unsafe Code Guidelines

1 Like

I have just run into exactly this problem as well. I tried reading the thread @mbrubeck linked, but AFAICT it is really a separate concern with making offsetting more ergonomic for raw pointers, but not touching on the main problem as I see it: without something like UnsafeDeref, built in types have a superpower that user types are not allowed to have. Without such a feature you can't define a type that is truly interchangeable with a raw pointer. Code that wants to be generic over raw pointers and MySpecialUserPointer will have to use a custom trait to make sure dereferencing always goes through an unsafe function that is not based on the usual * deref syntax.

1 Like

Yeah, I think I must have misread this post originally, because I can’t see now how my reply above is relevant.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.