Skip to content

Commit fbfc808

Browse files
committed
Rework documentation into examples
1 parent e91689c commit fbfc808

File tree

1 file changed

+46
-8
lines changed

1 file changed

+46
-8
lines changed

src/libcore/ptr.rs

+46-8
Original file line numberDiff line numberDiff line change
@@ -2483,14 +2483,6 @@ impl<T: ?Sized> Eq for *mut T {}
24832483
/// by their address rather than comparing the values they point to
24842484
/// (which is what the `PartialEq for &T` implementation does).
24852485
///
2486-
/// A reference in Rust is sometimes stored different than a raw
2487-
/// memory address. These cases are called fat pointers. A reference
2488-
/// to a slice must store both the address of the slice and the length
2489-
/// of the slice. A reference to an object satisfying a trait must
2490-
/// also point to the vtable for the trait's methods. Since this
2491-
/// function compares pointers in totality, careful consideration to
2492-
/// the type of the variable must be made.
2493-
///
24942486
/// # Examples
24952487
///
24962488
/// ```
@@ -2508,6 +2500,52 @@ impl<T: ?Sized> Eq for *mut T {}
25082500
/// assert!(five_ref == other_five_ref);
25092501
/// assert!(!ptr::eq(five_ref, other_five_ref));
25102502
/// ```
2503+
///
2504+
/// Slices are also compared by their length (fat pointers):
2505+
///
2506+
/// ```
2507+
/// let a = [1, 2, 3];
2508+
/// assert!(std::ptr::eq(&a[..3], &a[..3]));
2509+
/// assert!(!std::ptr::eq(&a[..2], &a[..3]));
2510+
/// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
2511+
/// ```
2512+
///
2513+
/// Traits are also compared by their implementation:
2514+
///
2515+
/// ```
2516+
/// #[repr(transparent)]
2517+
/// struct Wrapper { member: i32 }
2518+
///
2519+
/// trait Trait {}
2520+
/// impl Trait for Wrapper {}
2521+
/// impl Trait for i32 {}
2522+
///
2523+
/// fn main() {
2524+
/// let wrapper = Wrapper { member: 10 };
2525+
///
2526+
/// // Pointers are equal address
2527+
/// assert!(std::ptr::eq(
2528+
/// &wrapper as *const Wrapper as *const u8,
2529+
/// &wrapper.member as *const i32 as *const u8
2530+
/// ));
2531+
///
2532+
/// // Objects have equal addresses, but `Trait` has different implementations
2533+
/// assert!(!std::ptr::eq(
2534+
/// &wrapper as &Trait,
2535+
/// &wrapper.member as &Trait,
2536+
/// ));
2537+
/// assert!(!std::ptr::eq(
2538+
/// &wrapper as &Trait as *const Trait,
2539+
/// &wrapper.member as &Trait as *const Trait,
2540+
/// ));
2541+
///
2542+
/// // Converting the reference to a `*const u8` compares by address
2543+
/// assert!(std::ptr::eq(
2544+
/// &wrapper as &Trait as *const Trait as *const u8,
2545+
/// &wrapper.member as &Trait as *const Trait as *const u8,
2546+
/// ));
2547+
/// }
2548+
/// ```
25112549
#[stable(feature = "ptr_eq", since = "1.17.0")]
25122550
#[inline]
25132551
pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {

0 commit comments

Comments
 (0)