How does `std::ptr::NonNull` make itself covariant wrt T?

The docs for std::ptr::NonNull says that it is:

*mut T but non-zero and covariant

Is it correct that NonNull works around the covariant-ness rules by:

  1. Storing the inner pointer as *const T
  2. Casting it to *mut T when we want a mutable pointer/reference

Yes, it stores the pointer as a *const T.

For questions like these it's often insightful to look at the implementation itself:

Other than the rustc_nonnull_optimization_guaranteed and rustc_layout_scalar_valid_range_start annotations, there isn't much to NonNull that you couldn't write yourself. 90% of that file is just documentation and // SAFETY: comments.


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.