# Add initialization helper · gitcafe/zig

[View on GitCafe](https://git.cafe/gitcafe/zig/commit/c0e5eca6f2e1a688a6703ed36aef300d9393183d)

Repository: [gitcafe/zig](https://git.cafe/gitcafe/zig)

Visibility: public

Requested revision: c0e5eca6f2e1a688a6703ed36aef300d9393183d

Requested commit: c0e5eca6f2e1a688a6703ed36aef300d9393183d

Commit: c0e5eca6f2e1a688a6703ed36aef300d9393183d

Tree: a641af417f7e99f69083a8a2910d4d0c801ee86d

Author: Alexis Brodeur

Committer: Andrew Kelley

## Message

````
Add initialization helper

When using C libraries, C99 designator list initialization is often
times used to initialize data structure.

While `std.mem.zeroes` and manually assigning to each field can
achieve the same result, it is much more verbose then the equivalent
C code:

```zig
usingnamespace @cImport({
    @cInclude("sokol_app.h");
});

// Using `std.mem.zeroes` and manual assignment.
var app_desc = std.mem.zeroes(sapp_desc);
app_desc.init_cb = init;
app_desc.frame_cb = frame;
app_desc.cleanup_cb = cleanup;
app_desc.width = 400;
app_desc.height = 300;
app_desc.window_name = "no default init";

// Using `std.mem.defaultInit`.
var app_desc = std.mem.defaultInit(sapp_desc, .{
    .init_cb = init,
    .frame_cb = frame,
    .cleanup_cb = cleanup,
    .width = 400,
    .height = 300,
    .window_name = "default init"
});
```

The `std.mem.defaultInit` aims to solve this problem by zero
initializing all fields of the given struct to their zero, or default
value if any.  Each field mentionned in the `init` variable is then
assigned to the corresponding field in the struct.

If a field is a struct, and an initializer for it is present, it is
recursively initialized.

````

## Parents

- [937dcad0b3802863af0891b2766acb55f89949ba](https://git.cafe/gitcafe/zig/commit/937dcad0b3802863af0891b2766acb55f89949ba?format=markdown)

[Source at this commit](https://git.cafe/gitcafe/zig/tree/c0e5eca6f2e1a688a6703ed36aef300d9393183d?format=markdown)
