Storing arrays in structures

How do I store slices in structures in Zig?

I have a function call structure that stores an array of arguments.

pub const FunCall = struct {
    id: Ident,
    args: ArrayList(Atom),
};

pub const Atom = union(enum) {
    register: Register,
    register_index: RegisterIndex,
    constant: Constant,
    variable: Ident,
    macro_arg: Ident,
    data: void, // instruction data buffer
};

Is there a better way to do it than this?

        const data_id = IR.Ident{ .name = "get_data", .loc = field.id.loc };
        var data_temp = [_]IR.Atom{
            .{ .variable = idnoloc("data") },
            .{ .variable = idnoloc("offset") },
            .{ .variable = idnoloc("size") },
            .{ .variable = idnoloc("alignment") },
        };
        var data_args = ArrayList(IR.Atom).init(ir.alloc);
        try data_args.appendSlice(&data_temp);
        const get_data_expr = IR.Expr{
            .fun_call = .{ .id = data_id, .args = data_args },
        };

How do I store slices in structures in Zig?

args: []Atom

and then
.args = allocator.dupe(...)

1 Like

I assume you meant dupe, which in this case could be used like so:

const data_args = try ir.alloc.dupe(IR.Atom, &data_temp);

If there was a reason for needing the ArrayList, then toOwnedSlice is usually what you’d want to use instead:

var data_args = ArrayList(IR.Atom).init(ir.alloc);
defer data_args.deinit();
// ... append, etc ...
const data_args_slice = try data_args.toOwnedSlice();
2 Likes

Nvm it’s about nested ArrayLists, not nested arrays :slight_smile:

Eventually I would really like to see better struct-init ergonomics for nested arrays though, to bring the struct initialization features closer to what C99 can do (e.g. see: QoL: Partial array initialization in structs · Issue #6068 · ziglang/zig · GitHub)

…this would solve a lot of hairy ownership/lifetime problems with slices when copying structs with embedded slices (vs embedded arrays) around, since arrays are values while slices are references.

1 Like