Have `Allocator.create` take initialization value

Often, a call to Allocator.create is succeeded by an immediate initialization of the returned memory. My idea is to have create take an initialization value, and initialize the new memory itself. If you wanted to keep the prior behaviour, you would simply pass undefined as the initialization value.

const std = @import("std");

const Foo = struct {
    bar: i32 = 0,
    baz: bool = false,

    const init = Foo{ .bar = 10, .baz = true };
};

pub fn main() !void {
    var arena = @import("std").heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const before = try allocator.create(Foo, undefined);
    const default = try allocator.create(Foo, .{});
    const init = try allocator.create(Foo, .init);
    const custom = try allocator.create(Foo, .{
        .bar = -1,
        .baz = false,
    });

}

This has a two advantages:

  1. It is explicit when memory is undefined. It’s easy for newcomers to not realize ‘create’ returns undefined memory, without reading the doc comment (hence).
  2. It is easier to read and write in the case where you were going to immediately initialize anyway.

Win Win! Unless I’m missing something?

1 Like

There is an open proposal suggesting exactly this:

5 Likes

Whoops. That’s good to know, thanks.

Not pretty sure, but two “constructors” seem to be more or less close to the topic.