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 {};

6 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.

2 Likes

True! I encountered this too.

Good catch. Thx.