A small nitpicking inconsistency in Zig

I think it’s reasonable to design this kind of side effect scenario as illegal behavior.

I’ve also seen core members discussing controversial debates about the execution order of side effects, similar to this issue, and they are gradually leaning towards treating it as illegal behavior.

Tbh I hope that case is considered a language design bug and not intended behaviour:

    var a: Bla = .{ .a = 12, .b = 34 };
    a = .{ .a = a.b, .b = a.a };

(a.a and a.b values are 34 after the second assignment)

The assignment should either go through a temporary value (which then will be optimized away in most situations anyway), or it should be a clear error.

I think there is no other language which disolves such a struct assignment into per-member assignments like this? E.g. why allow struct assignments at all when it’s just syntax sugar for a sequence of multiple per-item assignments anyway:

    a.a = a.b;
    a.b = a.a;
5 Likes

You did not do the Bubble Sort? Not even once? How is it even possible?

That would be 2. on the list, which would be my preferred option after just supporting the swapping.

My issue with the error behavior, as mentioned, is I find it hard to believe its possible to correctly detect all instances of this without false positives.

  • a, b = .{ b, a } is the obvious case.
  • a, b = .{ foo(), a } less obvious, but still relies on the weird behavior.
  • a, b = .{ c.*, d.* } the killer. Whether it should be allowed depends on where c and d point to.

The last case was my main reason for opposition to the error solution (besides wanting to be able to do swaps like in other languages), but reading through the post @npc1054657282 linked catching it at runtime in that last case for debug (and maybe releaseSafe) builds does also seem like an acceptable option.

2 Likes

The accepted proposal remove result pointers from the language #32009 will change this behavior. Which is why the forms are becoming redundant, and the proposal to remove one of them is accepted. Swapping fields on structs not working is specifically called out as an undesired behavior that will be fixed.

4 Likes

As learning opportunity yes, but not production code.

1 Like

You may be correct, I’m just going off the docs.

Zig allows omitting the struct type of a literal. When the result is coerced, the struct literal will directly instantiate the result location, with no copy