Skip to content

Commit b85033a

Browse files
committed
Rollup merge of #31720 - frewsxcv:std-mem-transmute-copy-example, r=steveklabnik
Prior to this commit, it was a trivial example that did not demonstrate the effects of using the function. Fixes #31094
2 parents 216081d + 8f13f87 commit b85033a

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

src/libcore/mem.rs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -571,9 +571,25 @@ pub const POST_DROP_USIZE: usize = POST_DROP_U64 as usize;
571571
/// ```
572572
/// use std::mem;
573573
///
574-
/// let one = unsafe { mem::transmute_copy(&1) };
574+
/// #[repr(packed)]
575+
/// struct Foo {
576+
/// bar: u8,
577+
/// }
578+
///
579+
/// let foo_slice = [10u8];
580+
///
581+
/// unsafe {
582+
/// // Copy the data from 'foo_slice' and treat it as a 'Foo'
583+
/// let mut foo_struct: Foo = mem::transmute_copy(&foo_slice);
584+
/// assert_eq!(foo_struct.bar, 10);
585+
///
586+
/// // Modify the copied data
587+
/// foo_struct.bar = 20;
588+
/// assert_eq!(foo_struct.bar, 20);
589+
/// }
575590
///
576-
/// assert_eq!(1, one);
591+
/// // The contents of 'foo_slice' should not have changed
592+
/// assert_eq!(foo_slice, [10]);
577593
/// ```
578594
#[inline]
579595
#[stable(feature = "rust1", since = "1.0.0")]

0 commit comments

Comments
 (0)