Hacker News new | ask | show | jobs
by Kolja 1868 days ago
> I am curious to know the reasons behind the @as() syntax. What's wrong with "i32 y = (i32) x;"?

Built-ins in Zig are functions beginning with `@`. Your cast operator would be a new syntax construct, something Zig tries to limit as much as possible (keeping the parser simple).

> What type is "b"? i32?

That's easy, i32. Integer literals are of type comptime_int, which may coerce into other integer types if possible without loss of information, and since the only typed expression is the @as, every other integer in the line will coerce to its type.

1 comments

> That's easy.

For code that is not yours, or code that you open a year later, I think it's easier to specify the type. Exactly as when you see something like "var x = some_function();" and you need to know the type.

You can also use `@compileLog(@TypeOf(some_function))` or the same for the result. Type inference mostly makes it easier to change the types involved without having to update every single variable binding which would often be rather error prone in languages with implicit casts.

The other gain here is with duck-typing as being less explicit allows you to write more generic code which will often do what you want as long as the shape fits without `void*` which gives up on type safety.

Best practice for languages with this "var" approach is to use it when the type is obvious or irrelevant and to explicitly declare the type when it is non-obvious and relevant.

If you are reviewing code and can't instantly tell what the type is for a variable, ask the author to explicitly include the type. Problem solved.