#generic structure alternative syntax

1 messages · Page 1 of 1 (latest)

vagrant plaza
#

Looking into generics now, found this simple example

fn List(comptime T: type) type {
    return struct {
        pos: usize,
        items: []T,
        allocator: Allocator,

        fn init(allocator: Allocator) !List(T) {
            return .{
                .pos = 0,
                .allocator = allocator,
                .items = try allocator.alloc(T, 4),
            };
        }
    };
}

Is it possible to make this struct outside of the function?
Something like this instead:

const ListImpl: type = struct {
    ...
}

pub List(comptime T: type) type {
  return ListImpl{}
}

I'm not a fan of having to start everything double nested like this

wicked spear
#

Not really, since the inner type depends on the function parameters.

#

Like - if you could do that, you wouldn't need the List function in the first place.