Use *mut T rather than NonNull<T>, but why?

Standard Library of NonNull says

If you’re not sure if you should use NonNull<T> , just use *mut T !

Uh.... But why?

How can an aligned and non-null pointer untimately more dangerous to use than possibly non-aligned or possibly null pointer?

It's about the variance

Unlike *mut T , NonNull<T> was chosen to be covariant over T . This makes it possible to use NonNull<T> when building covariant types, but introduces the risk of unsoundness if used in a type that shouldn’t actually be covariant. (The opposite choice was made for *mut T even though technically the unsoundness could only be caused by calling unsafe functions.)


The actual reason is variance like the other answer explained, but to expand on the question:

You're right that if you're dereferencing a NonNull pointer you have more guarantees, hence it's less dangerous, but at the same time when you create a NonNull pointer you have to satisfy those guarantees yourself, hence making it more dangerous.

Also, a NonNull pointer is not guaranteed to be aligned.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.