#Create and use an array of std.ArrayList at compile time, all with different types.

1 messages · Page 1 of 1 (latest)

obsidian hawk
#

this doesn’t work

foggy holly
#

would an ordinary array work?

#

it looks like you have entirely comptime-known values here, so it should

#

ArrayLists are for allocated arrays, usually on the heap. As it stands, you can't allocate during comptime

obsidian hawk
#

you could likely construct a tuple of ArrayLists; but arrays must have a unified type, and std.ArrayList is not a type

#
pub fn GetArrayListTuple(comptime types: []const type) type {
  var arraylist_types: [types.len]type = undefined;
  for (types, 0..) |T, i| {
    arraylist_types[i] = std.ArrayList(T);
  }
  return std.meta.Tuple(&arraylist_types);
}

pub fn get_arraylists(comptime types: []const type) GetArrayListTuple(types) {
    var tuple: GetArrayListTuple(types) = undefined;
    inline for (tuple) |*member| {
      member.* = @TypeOf(member.*).init();
    }
    return tuple;
}

something like this should work

#

but I'd really reconsider how you're doing things if you're at this point of using reflection

foggy holly
#

most of the features in an ArrayList are there to support mutating them. But a comptime data structure isn't mutable, it goes into the .rodata portion of the binary

#

so you can make a fixed array-of-arrays, and then either make a mutable copy to an ArrayList by coercing slices, or just work with it directly if you don't need mutability

#

but you'd have to do the mutable part at runtime

obsidian hawk
foggy holly
#

I don't see you passing any runtime data into the original function at all though

obsidian hawk
#

But a comptime data structure isn't mutable
This isn't a comptime data structure, this is comptime logic to generate a structure that can be used at runtime

foggy holly
#

Oh. so a type?

obsidian hawk
#

in particular initializing such a type

foggy holly
#

you can generate a type at runtime, but you aren't doing that

obsidian hawk
#

you can generate a type at runtime
no

foggy holly
#

typo, meant 'at comptime'

#

does the data exist at runtime, or comptime?

obsidian hawk
obsidian hawk
#

yeah... choose a better allocator and that's all good

#

yes