Skip to content

Commit 18f41e5

Browse files
committed
Suggest direct raw-pointer dereference
People often come looking for some kind of `as_ref_unchecked` method on raw pointers that would give them `&T` and not `Option<&T>` when they are sure the pointer is not NULL. There's no such method, but taking a reference of the dereferenced pointer accomplishes the same thing. Therefore, suggest using that, at the `as_ref` site ‒ it's a place people are likely going to look into.
1 parent a9d4967 commit 18f41e5

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/libcore/ptr.rs

+30
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,21 @@ impl<T: ?Sized> *const T {
582582
/// }
583583
/// }
584584
/// ```
585+
///
586+
/// # Null-unchecked version
587+
///
588+
/// If you are sure the pointer can never be null and are looking for some kind of
589+
/// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>, know that you can
590+
/// dereference the pointer directly.
591+
///
592+
/// ```
593+
/// let ptr: *const u8 = &10u8 as *const u8;
594+
///
595+
/// unsafe {
596+
/// let val_back = &*ptr;
597+
/// println!("We got back the value: {}!", val_back);
598+
/// }
599+
/// ```
585600
#[stable(feature = "ptr_as_ref", since = "1.9.0")]
586601
#[inline]
587602
pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
@@ -1303,6 +1318,21 @@ impl<T: ?Sized> *mut T {
13031318
/// }
13041319
/// }
13051320
/// ```
1321+
///
1322+
/// # Null-unchecked version
1323+
///
1324+
/// If you are sure the pointer can never be null and are looking for some kind of
1325+
/// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>, know that you can
1326+
/// dereference the pointer directly.
1327+
///
1328+
/// ```
1329+
/// let ptr: *mut u8 = &mut 10u8 as *mut u8;
1330+
///
1331+
/// unsafe {
1332+
/// let val_back = &*ptr;
1333+
/// println!("We got back the value: {}!", val_back);
1334+
/// }
1335+
/// ```
13061336
#[stable(feature = "ptr_as_ref", since = "1.9.0")]
13071337
#[inline]
13081338
pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {

0 commit comments

Comments
 (0)