Working with strings in array... "unable to resolve comptime value"

I’m trying to create a loop over file names, essentially to avoid repeating code in build.zig. This is what I’ve tried:

const std = @import("std");

pub fn main() void {
    const generators = [_][]const u8{ "chromosome_generator", "bool_chromosome_generator", "bitset_chromosome_generator" };
    for (generators) |g| {
        const path = "src/" ++ g ++ ".zig";
        std.debug.print("Building: {}\n", .{path});
    }
}

This fails, however, with:

examples/comptime_array.zig:6:32: error: unable to resolve comptime value
        const path = "src/" ++ g ++ ".zig";
                               ^
examples/comptime_array.zig:6:32: note: slice value being concatenated must be comptime-known

I guess it’s all a matter of generating a comptime-known static array. No matter how I’ve tried, I haven’t managed to pull it off. If I set statically the string length, for instance, since lengths differ it fails with a different error.

I’ve tried also with BufPrint, with a different error (essentially, error{NoSpaceLeft}). Any help will be much appreciated.

Slice concatenation (++) is comptime only.
You can concatenate the strings using std.mem.join and the paths using std.fs.path.join

const std = @import("std");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();
    defer _ = gpa.deinit();
    const generators = [_][]const u8{ "chromosome_generator", "bool_chromosome_generator", "bitset_chromosome_generator" };
    for (generators) |g| {
        const file = try std.mem.join(allocator, ".", &.{g, "zig"});
        defer allocator.free(file);
        const path = try std.fs.path.join(allocator, &.{
            "src",
            file
        });
        defer allocator.free(path);
        std.debug.print("Building: {s}\n", .{path});
    }
}
1 Like

An alternative is to stay in comptime using inline for.

const std = @import("std");

pub fn main() void {
    const generators = [_][]const u8{ "chromosome_generator", "bool_chromosome_generator", "bitset_chromosome_generator" };
    inline for (generators) |g| {
        const path = "src/" ++ g ++ ".zig";
        std.debug.print("Building: {s}\n", .{path});
    }
}
1 Like