#Build a list of types at comptime

1 messages · Page 1 of 1 (latest)

somber jay
#

I though something like the following code would work, but when I try to test it, getTypes returns an empty slice:

pub fn Scheme(comptime name: []const u8) type {
    comptime var types: []const type = &[_]type{};
    return struct {
        pub const scheme_name = name;

        pub fn addType(comptime Type: type) void {
            if (Type.Scheme != @This()) {
                @compileError("some message");
            }

            types = types ++ &[_]type{Type};
        }
        
        pub fn getTypes() []const type {
            return types;
        }
    };
}
supple sable
#

I'm not really sure why it even lets you touch types like that and reference it after the function has ended.

sour patio
#

closure over comptime var is illegal

#

that's meant to be a compile error

#

guess that one slipped through the cracks

#

it used to work, but wreaked havoc on compile times and incremental compilation

somber jay
#

is there an alternative for this use case?

#

The use case being, I need to build up a list of types that are part of a 'scheme'

#

I can explicitly pass the types to the Scheme function, but it'd be easier to use if I could do it the other way around, where the type adds itself to the scheme.

sour patio
#

could just have it as a field

#

though that does make it comptime-only

#

and effectively becomes a glorified arraylist for types

supple sable
#

@typeName(T: type) *const [N:0]u8
TypeName isn't constrained by comptime. You could probably make an ArrayList of those (names) if you simply need to check if a type is in the scheme and not need any extra data.

somber jay
#

hmm, let me try the comptime field solution

#

I do need to reference the types themselves after the fact

#

Thanks for the help guys

silent flume