Search code examples
zig

How do I initialize a slice of slices in Zig?


I'm trying to initialize a slice of slices of strings -- i.e. a [][][]const u8, but it doesn't seem to be possible:

var x: [][][]const u8 = [][][]const u8{};

This the compiler to say: error: type '[][][]const u8' does not support array initialization syntax.

var x: [][][]const u8 = .{};

This works with slices of one or two levels apparently, but not here: error: expected type '[][][]const u8', found '@TypeOf(.{}).


I wanted to know how to initialize it with some elements inside, but I can't even initialize an empty one!


Solution

  • An empty slice can be easily created using the &.{} syntax. For example:

    var x: [][][]const u8 = &.{};
    

    But if you try to initialize it with elements inside, you'll get errors. You'll have to make the slices const, for example:

    var y: []const []const u8 = &.{
        "hello",
        "world",
    };
    
    var z: []const []const []const u8 = &.{
        &.{
            "hello",
        },
        &.{
            "world",
        },
    };
    

    Or use an allocator:

    var w: [][][]const u8 = try allocator.alloc([][]const u8, 10);
    defer allocator.free(w);
    // ...