Size Of Struct Member

How does one go about in getting the size of a struct member. The below code works but only due to it being able to use the member via the instance of TransportHeader.

pub fn size(flags: u32) u16 {
        const t = TransportHeader {};
        var res : u16 = 0;
        if (Flags.hasTag(flags)) {
            res += @sizeOf(@TypeOf(t.messageNo));
        }
        return res;
    }
}

The following does not work:

return @sizeOf(TransportHeader.messageNo);
return @sizeOf(@TypeOf(TransportHeader.messageNo));

It is obvious that a non static member is not accessible without an instance (or similar), at least in these circumstances, so my gut is telling me that I am missing some magic.

You can use @FieldType(comptime T: type, comptime field: [] const u8) type.

Before this builtin I used @TypeOf(@as(T, undefined).field).

3 Likes

Thank you. Will check it out immediately.

@Dok8tavo

return @sizeOf(@FieldType(TransportHeader, "messageNo"));

Big thank you. Your recommendation works. I was not expecting this type of “member” as string to be the solution, but makes 100% sense given the problem.

Just for giggles?

Before this builtin I used `@TypeOf(@as(T, undefined).field)`.

How would this code look; as does it not assume that you know the resulting type already?

return @sizeOf(@TypeOf((@as(TransportHeader, undefined).messageNo)));

Thanks got it…

I was wondering if that could be done directly or if that would be impossible.
@SizeOf(MyStruct.substruct.field). Would be cool.

@sizeOf takes in a type. There is no getting around it. But you could write a function like this:

inline fn sizeOf(value: anytype) comptime_int {
   return @sizeOf(@TypeOf(value));
}