Generic struct with factory

Trying to re-learn zig after a hiatus.

I’m trying to create a generic object pool that maintains a factory function. A simplified example would be:

pub fn Pool(comptime T: type) type {
    return struct {
        size: i32,
        factory: fn () anyerror!T,

        const Self = @This();

        pub fn init(size: usize, factory: fn () anyerror!T) Self {
            return .{
                .size = size,
                .factory = factory,

        pub fn create(self: *Self) !T {
            return self.factory();

But this fails to compile (I’m using 0.10.0-dev.4192+c75e8f361). It says my factory: fn () anyerror!T parameter to init has to be comptime, but if I mark is as comptime, it then complains that all parameters (e.g. size) also need to be comptime.

Maybe using function pointer will help?

const factoryFnPtr = *const fn() !T;
factory: factoryFnPtr;
1 Like