For a struct member its possible to calculate the offsetof
in Rust, similar to C's offsetof
.
While this works for struct fields, I couldn't find an equivalent of how to do this for enums and their variant members.
From talking to developers on IRC its not guaranteed that all members of an enum are aligned:
How to calculate the offset of an enum member?
With instances it could work like this:
enum Test { A(u8), B(f64) };
fn test_me(a: Test) {
if let Test::A(b) = a {
// we could find the offset between 'a' and 'b' here.
// but how to do this without instantiating variables?
println("{}", (b as *const _) as usize - (a as *const _) as usize);
}
}
However the aim is to be able to do this by inspecting only the type, so it could compile down to a constant, eg:
println("{}", offset_of_enum!(Test, A));
While attempting to write a macro for this I ran into problems joining the arguments by ::
so I wasn't sure how to resolve that part.