How to initialize a struct in a heap

Hello, community.

I’m now writing a USB driver in Zig (and I’m feeling Zig is a great language…!).
In this area, it’s common that we have to place a struct in the specified pre-allocated heap (or somewhere) region:

const SomeStruct = packed struct (u16) {
    fa: u8,
    fb: u8 = 3,

    pub fn init(mem: [*]u8) void {
        const self: *SomeStruct = @alignCast(@ptrCast(mem));
        self.fa = 9;
        self.fb = 3;

I wonder that is there any convenient way to initialize a struct when we have a pointer to the memory to put the struct. It’s like new keywords does in C++.
I want it to:

  • Allow struct initialization syntax: .{ .fa = 2, .fb = 3 }
  • Set the default value when the field’s value is not given.

I really appreciate your opinion and kind help :slight_smile:

Probably, this doc should help.


Oops, I forget that we can use ptr.* = SomeStruct{} syntax! Thank you! :slight_smile:

1 Like

I think your @ptrCast+@alignCast is most of it, you might want to follow that up with zeroInit and use its init argument to set some of the fields that you want to initialize to different values.

Note that zeroInit defaults values to zero, where the ptr.* = SomeStruct{} syntax would force you to provide the fa field initialization value explicitly, because it has no declared default.

1 Like

Wow, this is another thing I was looking for…! Though I can’t use this function in this case cuz I want to use many non-default values for initialization, I think this function is really useful! Big thanks.

I think in most cases it is better to use ptr.* = SomeStruct{} (if that is enough), but sometimes zeroInit is what you actually want.

1 Like