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

1.7k views Asked by At

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?

2

There are 2 answers

0
sigod On BEST ANSWER

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 }
0
matejcik On

as of Zig 0.11 (dunno when this was introduced), you can use the pattern repeat operator ** like so:

const array_of_zeroes = [_]u32{0} ** 10;

This works with more complicated contents, too:

const things = [_]Thing{Thing.init()} ** 10;
const text = "ab" ** 15;  // ababababab...