Zig NEWS

loading...

Discussion on: What's a String Literal in Zig?

Collapse
david_vanderson profile image
David Vanderson

Thanks - great to see different options for how to do it!

Can you think of a way to use the helper function and somehow infer the size of the struct member so it doesn't have to be repeated? Not a huge deal but I can't figure out how to do it.

Thread Thread
mrkishi profile image
mrkishi

I don't know how to do that exactly. The closest I could come up with would be to leave the array undefined and use a helper function to fill it in, but that has slightly different semantics since the memcpy is a little more explicit:

fn init_array(target: anytype, items: ?[]const std.meta.Elem(@TypeOf(target))) void {
    const T = std.meta.Elem(@TypeOf(target));
    if (items) |slice| {
        std.mem.copy(T, target, slice);
        std.mem.set(T, target[slice.len..], std.mem.zeroes(T));
    } else {
        std.mem.set(T, target, std.mem.zeroes(T));
    }
}

var foo: [50]u8 = undefined;
init_array(&foo, "foo");

var a = A{.foo = undefined};
init_array(&a.foo, "foo");
Enter fullscreen mode Exit fullscreen mode
Thread Thread
david_vanderson profile image
David Vanderson

Good solution. I haven't seen std.meta.Elem before so I'm going to go read up on that. Thanks!