Function std::mem::transmute_copy
pub unsafe fn transmute_copy<T, U>(src: &T) -> U
Interprets src
as having type &U
, and then reads src
without moving the contained value.
This function will unsafely assume the pointer src
is valid for size_of::<U>
bytes by transmuting &T
to &U
and then reading the &U
(except that this is done in a way that is correct even when &U
makes stricter alignment requirements than &T
). It will also unsafely create a copy of the contained value instead of moving out of src
.
It is not a compile-time error if T
and U
have different sizes, but it is highly encouraged to only invoke this function where T
and U
have the same size. This function triggers undefined behavior if U
is larger than T
.
Examples
use std::mem; #[repr(packed)] struct Foo { bar: u8, } let foo_array = [10u8]; unsafe { // Copy the data from 'foo_array' and treat it as a 'Foo' let mut foo_struct: Foo = mem::transmute_copy(&foo_array); assert_eq!(foo_struct.bar, 10); // Modify the copied data foo_struct.bar = 20; assert_eq!(foo_struct.bar, 20); } // The contents of 'foo_array' should not have changed assert_eq!(foo_array, [10]);
© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/mem/fn.transmute_copy.html