Get type of a declaration

Hello,
I am currently trying to calculate the maximum size among a few different types. All of which I have included in the file structs.zig. The file looks something like this

pub const FirstStruct = @import("example_struct.zig");
// ... with more declarations below

and example_struct.zig is just a struct

field_1: u8,
const name = "This is a name";

The way I initially tried to do this was by doing

const max_size: usize = b: {
    var running_max = 0;

    // Contains declarations for different structs
    const structs = @import("structs.zig");
    for (@typeInfo(structs).@"struct".decls) |decl| {
        // -- TODO: Get type of decl
        const DeclType: type = ???;

        running_max = @max(@sizeOf(DeclType), running_max);
    }

    break :b running_max;
};

However, there doesn’t seem to be a way to get the type of a declaration just using the Declaration. Which only contains the declaration name.

Is this actually possible somehow? Or is there another way to accomplish what I am trying to do here, without doing it this way? Thanks.

sidenote: New to the language, have been using it to do a few gamedev things. It’s been a really fun experience. Thanks again!

I think that @field(first_struct, "name") should give you the pointer you’re looking at, so in all I would do

@sizeOf(@TypeOf(@field(parent_struct, decl_name)))

to get the size of the type of a decl whose name is in the comptime-known string decl_name.

3 Likes

Oh I see. You can use @field for declarations as well. It seems to have worked.

The @TypeOf is unnecessary in the following example since the declaration of example_struct is in itself a type.

const max_size: usize = b: {
    var running_max = 0;

    const structs = @import("structs.zig");
    for (@typeInfo(structs).@"struct".decls) |decl| {

        running_max = @max(@sizeOf(@field(structs, decl.name)), running_max);
    }

    break :b running_max;
};

Thanks again!

1 Like