#Grokking the .init; syntax

1 messages · Page 1 of 1 (latest)

coral blade
#

I'm trying to understand this syntax:

var debug_allocator: std.heap.DebugAllocator(.{}) = .init;

For me, this does not 'parse' yet, especially omitting parenthesis after .init - I would have expected:

var debug_allocator: std.heap.DebugAllocator(.{}) = .init();

What I do understand:

// debug_allocator is of type std.heap.DebugAllocator
// The DebugAllocator is a comptime function, and .{} means "infer type and use default values"```

However, I just cannot 'get' that `.init;` may omit parenthesis. The dot means 'call fn in the struct, infer type' **but it is a call - not a value.**

This to me seems to 'implicit' and goes against some of the explicitness I've come to like with Zig. Please help me understand!
marble crown
#

init on debug allocator is a constant

#

the dot syntax works on any declaration

#

actually idk if it works on var decls but enum variants, functions that return that struct or consts that are of type that struct can be used with dot syntax

coral blade
#

Oh, that obvious - thanks! 😄

For completeness, could you give examples of those things you mentioned?

#

For some reason I had gotten to understand init fn's as the convention for 'constructing' structs (like constructors in other languages) - didn't occur to me it may not need to be a fn at all!

placid cairn
#
const Foo = struct {
    items: [8]u32 = @splat(0),
    elems: usize = 0,

    const empty = Foo{};

    pub fn fullOf(x: u32) Foo {
        return .{
            .items = @splat(x),
            .elems = 8,
        };
    }
};

var foo: Foo = .empty;
var bar: Foo = .fullOf(5);
var ful: struct {
    c: Foo,
} = .{
    .c = .fullOf(2),
};

pub fn main() !void {
    @import("std").debug.print("{}\n{}\n{}\n", .{ foo, bar, ful });
}
#

It makes it all a lot more concise, especially when it's a type a few structs deep, you can imagine.

#

.init or init() is just naming convention.

#

Trying with a var gives error: decl literal must be comptime known.

coral blade
terse nova
#

for empty. decl literals are a huge timesaver when you don’t want to respecify a type that’s already known (i.e. bc it is the member of a struct).

placid cairn
#

it would be better if you created a new post instead. Because this is not relevant to the topic.