How are "initializers" actually implemented

If there is an init function like this:

pub const Data = struct {
  buffer: [4096]u8,

  pub fn init() Data {
    return .{ .data = std.mem.zeroes([4096]u8) };
  }
};

var d = Data.init();

How many times will be the memory backing the struct copied? Or is the compiler smart enough to do it without any copy at all? And if so, is it guaranteed that there will be no copying done?

good question! I also want to know.

None

see: Result Location Semantics

3 Likes

Thank you for the reference. So there is actually a difference if I use .{} Or T{}. The former has assigned result location and will not copy, the later does not and will copy.

.{} is the preferred way.
T{} can assign a result location and not copy, but there are limitations.
see: What output do you think this has, and what do you think it should have / wish it had? - #9 by mlugg

3 Likes