ACP: Add from_ref
and from_mut
constructors to core::ptr::NonNull
.
#448
Labels
ACP-accepted
API Change Proposal is accepted (seconded with no objections)
api-change-proposal
A proposal to add or alter unstable APIs in the standard libraries
T-libs-api
Proposal
Problem statement
To create a
core::ptr::NonNull
object from a reference, one can simply use the providedFrom
implementation. But in constant expressions (const
functions/blocks), trait methods are (mostly) forbidden, and one currently has to resort to more complicated work arounds.Motivating examples or use cases
To circumvent the trait restrictions, one could instead first create a raw pointer and then construct the relevant non-null pointer from the raw pointer:
with
raw_ref_op
, however, this can be simplified to the following:But this is still unnecessarily complicated for an operation that should be a no-op.
Solution sketch
I propose adding the
from_ref
andfrom_mut
constructors for parity with the similar global functions incore::ptr
:Which would allow directly constructing a non-null pointer like the following:
The latter constructor is inherently unblocked by the stabilisation of
const_mut_refs
.Alternatives
An alternative solution would be to directly allow primitive casts to the
NonNull
type:Although I doubt this would actually be preferred over the primary solution.
Another alternative would be to allow traits in constant expressions, but this is already covered by
const_trait_impl
.Links and related work
The #130822 PR implements the
from_ref
andfrom_mut
constructors behind thenon_null_from_ref
feature gate. The #130823 issue tracks this feature gate.The text was updated successfully, but these errors were encountered: