Skip to content

Zig Snippets

shazz edited this page Jan 16, 2023 · 2 revisions

Resources

Generate structs at comptime

As arrays size need to be known at comptime, using metaprogramming, it is possible to generate the Struct at comptime and especially set the array length.

const std = @import("std");
const expect = @import("std").testing.expect;

const data_b = @embedFile("random.dat");

const MySubStruct = struct {

    value: u32 = undefined, 
};


fn MyStruct(
    comptime nb: comptime_int,
) type {
    return struct {

        mystring: []const u8 = undefined,
        table: ?[]const u8 = undefined,
        subs: [nb]MySubStruct = undefined,
        const Self = @This();

        fn print(self: Self) void {
            std.debug.print("mystring: {s}\n", . {self.mystring});
            std.debug.print("mystring len: {}\n", . {self.mystring.len});

            std.debug.print("subs len: {}\n", . {self.subs.len});
            std.debug.print("subs[0] int value: {}\n", . {self.subs[0].value});

            if (self.table) |t| {
                std.debug.print("table: {s}\n", . {t});
                std.debug.print("table len: {}\n", . {t.len});
            } else {
                std.debug.print("table is not defined\n", . {});
            }

        }

        fn init(data: []const u8, table: ?[]const u8) Self {

            var ms = Self{};
            ms.mystring = data;
            if (table) |t| {
                ms.table = t;
            }

            return ms;  
        }     
    };
}

pub fn main() !void {
   
    var start: u8 = 0;
    std.debug.print("start ptr: {}\n", .{ &start} );

    var test_str = MyStruct(100).init(data_b, data_b[0..10]);
    test_str.print();

    var end: u8 = 0;
    std.debug.print("end ptr: {} delta: {}\n", .{ &end, @ptrToInt(&end) - @ptrToInt(&start)} );

}
Clone this wiki locally