Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created July 16, 2019 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/2011c7455c725938b3edb33560c177d1 to your computer and use it in GitHub Desktop.
Save rust-play/2011c7455c725938b3edb33560c177d1 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#[derive(Debug)]
#[repr(C)]
struct MyStruct<T, U> {
height: Option<T>,
width: Option<T>,
age: u32,
othertype: U,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut value: MyStruct<i32, u8> = MyStruct {
height: Some(22003),
width: None,
age: 100,
othertype: 25u8,
};
println!("value == {:#?}", value);
let value_bytes =
unsafe { &mut *(&mut value as *mut MyStruct<i32, u8> as *mut [u8; std::mem::size_of::<MyStruct<i32, u8>>()]) };
println!("value_bytes = {:?}", value_bytes);
let value_reconstructed =
unsafe { &mut *(value_bytes as *mut [u8; std::mem::size_of::<MyStruct<i32, u8>>()] as *mut MyStruct<i32, u8>) };
println!("value_reconstructed == {:#?}", value_reconstructed);
println!("Modify value_reconstructed");
value_reconstructed.height = None;
value_reconstructed.age = 101;
value_reconstructed.width = Some(35);
println!("value_reconstructed == {:#?}", value_reconstructed);
println!("value == {:#?}", value);
println!("value_bytes = {:?}", value_bytes);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment