Search code examples
arraysbyteslicezerozig

Is there a way to initialize an array or slice of bytes to zeroes in Zig?


Apparently Zig used to provide this feature in an easy way, but it was removed in 6a5e61.

What is the recommended approach now for when such a behavior is needed? To manually iterate through the array/slice and set all bytes to zero?


Solution

  • Use std.mem.zeroes. Or use @memset.

    For example:

    var a: [10]u8 = undefined;
    @memset(&a, 0);
    // or
    // var a = std.mem.zeroes([10]u8);
    
    std.log.info("{any}", .{ a });
    

    This prints:

    info: { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }