"comptime struct + method injection"

This just works:

const std = @import("std");

const Storage = struct {
    count: usize = 0,
    fn store(self: *Storage) void {
        self.count += 1;
        std.debug.print("hello {}, ", .{self.count});
    }
};

fn Gen(comptime S: type) type {
    return struct {
        const Self = @This();

        storage: *S,

        fn init(storage: *S) Self {
            return Self{
                .storage = storage,
            };
        }

        fn store(self: *Self) void {
            self.storage.store();
        }
    };
}

fn test_storage() void {
    var storage = Storage{};
    var mg = Gen(Storage).init(&storage);
    mg.store();
    mg.store();
    mg.store();
}

pub fn main() !void {
    test_storage();
}

The only pub that is needed is for the main function, as soon as you separate pieces of the code across multiple files you need pub.

2 Likes