Coding style of initializing things

What do you like the best, regarding readability?

var thing: Thing = .init(args); // this?

var thing = Thing.init(args); // or this?

This one seems to much to me:

var thing: Thing = Thing.init(args); // too much.

However sometimes things are inferred:

var gpa = std.heap.smp_allocator; // not sure what this is.

So I prefer:

var gpa: std.mem.Allocator = std.heap.smp_allocator;

I never write:

const x = 42;

instead:

const x: i32 = 42;

There are more examples to think of of course :slight_smile:
Do people have “inner laws” for these little quirks when writing code?

1 Like

just by the way, you should do const gpa = std.heap.smp_allocator.

I much prefer var thing: Thing = .init(args); I think it’s my favorite new bit of syntax since I first learned const Name = struct {};

7 Likes

const x = 42 means x would implicitely be of type comptime_int, same with comptime var x = 42;. So with explicit typing it would be const x: comptime_int = 42;. I like that zig infers the type in those cases.

2 Likes

I think the var thing: Thing = .init(args) is currently tbe preferred way, but it has one huge flaw: when you need to catch the init error, then it is imposdible to use. Which makes me very sad any time it happens to me.

7 Likes

True! I encountered this too.

Good catch. Thx.

agree with everyone I much prefer var foo : Foo = .init(); but it’s annoying when the thing has error, I also like the var foo : Foo = .default or .empty pattern looks really clean

I’ve actually been trying to use var thing = Thing.init(args) more since I read Hoping to get feedback from veteran zig developers(for educational reasons) - #2 by matklad

I like the idea of grep-ability and how close the method is to it’s caller.

2 Likes

To TL:DR the link, I use x = .unique_name(...) a lot

.one_way_delay_mean = .ms(250),

But it is literally called init, then I always spell it full:

self.clock = Clock.init(...);

The reason is that the lines where you create a new instances of thing are fewer and more important that the lines where you mutate or read thing. I like to find those critical lines with a dumb text search.

19 Likes

That is exactly why I ran / run into doubts: dumb text search on .init() is useless. If you want to find all places where a certain thing is initialized you have to have some unique personal way identifying these places.

Yeah! I like var thing: Thing = .init(args); too. But it always discourages me when catch is not allowed.