How to create arrays during compile time in zig

I’m very new to zig and finding hard to create array during compile time.
I want to create error type during compile time. Below is a sample code.

const std = @import("std");

pub fn get_error() !type {
    // Cannot initialize with a fixed length array as the error names are fetched from a different file.
    var GP = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = GP.allocator();
    var error_codes = std.ArrayList(std.builtin.Type.Error).init(allocator);
    
    try error_codes.append(.{ .name = "Error1" }); // Think Error1 is the name fetched from the file.

    return @Type(.{ .ErrorSet = try error_codes.toOwnedSlice() });
}

test "error_codes" {
    const error_type = comptime get_error();
    _ = error_type;
}

Click test after opening this link for running above code

  • It is not clear what you want. The error strings are read from a file? In that case, I don’t think it can be done at compile time. You probably need to have your code generated by a program, then @import it.

    – 

Leave a Comment