Transmutes transformation of 015 rust Necromancer


The video recorded in this series is mainly on station BRust necromancer learning video

Rust necromancer related source information…


MEM:: transmute < T, u > takes a value of type T and resolves it back to type U. T and u are required to be the same size.
This kind of operation is unsafe and may result in undefined behavior.


1. Byte to type conversion

u32::from_ ne_ Bytes conversion from memory to native byte sequence type
u32::from_be_bytes  Conversion from memory to large end sequence type
u32::from_ le_ Bytes conversion from memory to small end sequence type


pub const unsafe extern "rust-intrinsic" fn transmute<T, U>(e: T) -> U
Reinterprets a value of one type to another. It copies the bits from the source value to the destination value, and then forgets the original value.


//Converting consecutive bytes to another type produces the behavior defined for

fn main() {
    //let raw_bytes = [0x78, 0x56, 0x34, 0x12];
    let mut raw_bytes = [0x78, 0x56, 0x34, 0x12];
    let num = unsafe {
        std::mem::transmute::<[u8; 4], u32>(raw_bytes)
    let ret = u32::from_ne_bytes(raw_bytes);

    //assert_eq!(num, 0x12345678);
    assert_eq!(num, ret);
    println!("num = {}", num);


pub unsafe fn transmute_copy<T, U>(src: &T) -> U
Interpret SRC as & U type and read the value of SRC. When reading, a copy is created, not moved directly.


use std::mem;

struct Foo {
    bar: u8,

fn main() {
    let foo_array = [10u8];

    unsafe {
        let mut foo_struct: Foo = mem::transmute_copy(&foo_array);
        assert_eq!(, 10); = 20;
        assert_eq!(, 20);

    assert_eq!(foo_array, [10]);

This work adoptsCC agreementReprint must indicate the author and the link of this article

Linghu Yichong