In the next stable Rust version, you can get the offset of a field through a MaybeUninit<Struct>
using the addr_of
macro, so you don't need to require that the type implements Default
.
macro_rules! get_offset {
($type:ty, $field:tt) => ({
let dummy = ::core::mem::MaybeUninit::<$type>::uninit();
let dummy_ptr = dummy.as_ptr();
let member_ptr = unsafe{ ::core::ptr::addr_of!((*dummy_ptr).$field) };
member_ptr as usize - dummy_ptr as usize
})
}
fn main(){
dbg!(get_offset!((String, String), 0));
dbg!(get_offset!((String, String), 1));
}
[src/main.rs:13] get_offset!((String, String), 0) = 0
[src/main.rs:14] get_offset!((String, String), 1) = 24