Hacker News new | ask | show | jobs
by ozgrakkurt 2 hours ago
> Take the address and deref afterwards, and it's exactly the same.

It is significantly worse to take address and deref afterwards.

You have to do something like:

@as(const u32, @ptrCast(&x)).

instead of just

@bitCast(x)

> Yes, and this is one reason @bitCast was changed to have different semantics that are not trivially achieved with @ptrCast.

This makes sense except breaking existing code that properly handled endianness by doing a conditional @byteSwap. And what you end up with is a more complicated intrinsic compared to something that reinterprets values with same layout size

2 comments

> This makes sense except breaking existing code

Before Zig hits 1.0, users should expect language changes. Has anyone claimed otherwise?

If you need the old thing often enough, you can write a wrapper for it. It's a trivial one-liner, as you've shown.

Your example is incorrect. @ptrCast has the same (similar, if you want to be pedantic to the exclusion of good faith) result rules. If you need @as to @ptrcast, you'd need it to @bitCast as well.

> It is significantly worse to take address and deref afterwards.

How are you measuring worse? Because my understanding from the article is that's exactly the behavior @bitCast used to have. So, instead of worse, it'd be exactly the same?

If you mean it's simply more things that you have to type... You're describing a core language feature as "worse". For all the builtins, some of them can help the compiler emit better code, but can for some doesn't mean will for all. As an example

    const thing: f64 = @floatFromInt(int_ish);
    const result = thing + other_float;
    return @intFromFloat(result);
Could zig auto convert between these types? Yes, absolutely. But it doesn't as a design decision. On some arch, converting between float and int can be very expensive. A competent engineer will ensure they're type converting in a reasonable order. Zig requires this painfully verbose syntax it order to make it painful. Are there times where it's is actually the only reasonable option? yes, but even if there wasn't it'd still need to exist because I'm not rewriting my whole program to avoid a single float conversion. But because it's a bit painful, I will rewrite this one function to make it less painful.

And, yes having already made that exact mistake... I now write better code from the start because there's no way I'm gonna ruin all my beautiful code with a bunch of ugly, annoying, hard to read, casts.

I used to complain about unused variable errors, unhandled enum branch, var unmodified (hint: use const) errors, hell even result ignored or error ignored when I'm trying to test some unrelated single line of code. But now that I'm used to them, I emit better code without thinking. It's made me a better programmer. Is it annoying? abso-fucking-lutely but I'm better now than I used to be, so: worth it; and: thankyou sir can I have another. :D