Filling a struct with zeroes

I have a (big) struct with some arrays in it.
Is there a better way to clear it than this?

fn clear(self: *SomeStruct) void {
    const bytes: []u8 = @ptrCast(@constCast(self));
    @memset(bytes, 0);
}

std.mem.zeroes

Try to avoid it, it’s mostly for C interop and the Zig way is to initialize each field to communicate intent

When initializing your fields, you may find @splat(0) useful

Yes but std.mem.zeroes returns a value.

self.* = std.mem.zeroes(SomeStruct);

I am afraid this is rather costly. I have to clear the struct more than one time (not only when initializing).

In that case I guess it’s fine if you insist on zero-init everything rather per field.

You can drop the @constCast.

1 Like

With optimization that doesn’t matter, the call is ‘resolved’ to the optimal form:

2 Likes

Thanks!

The struct is rather large. Using std.mem.zeroes just looks nicer than a bitcast.
I will change it.

const SmallValue = i16;
const History = struct {
    const CORRECTION_HISTORY_SIZE: usize = 16384 * 2;
    const CorrectionTable = [2][CORRECTION_HISTORY_SIZE]SmallValue;

    piece_to: [12][64]SmallValue,
    continuation: [12][64][12][64]SmallValue,
    pawn_correction: CorrectionTable,
    non_pawn_white: CorrectionTable,
    non_pawn_black: CorrectionTable,
};

BTW: just like in other languages (except Delphi) I really miss ‘typed length’ arrays.
Wouldn’t this be nice?

continuation: [Piece][Square][Piece][Square]SmallValue,

@ptrCast and @constCast should be dead giveaways that you’re doing something funky. Why do you have @constCast in there anyway?

2 Likes

The @constcast was a leftover from older times. No clue why it was there.
The @ptrCast was my try to fill the struct with zeroes in the most economic way.