Is there any syntax sugar for swapping variables in Zig? (e.g. a, b = b, a)
I expected
const std = @import("std");
pub fn main() void {
var a: i32 = 42;
var b: i32 = 69;
std.debug.print("{}, {}\n", .{ a, b });
a, b = .{ b, a };
std.debug.print("{}, {}\n", .{ a, b });
}
to work, but it outputs
$ zig build run
42, 69
69, 69
which is confusing.
Explaining what’s going on here, and whether there’s a syntax sugar will be really appreciated!
Depending on the situation, I sometimes prefer to not swap the original variables but rather have swapped versions. For example:
const reverse : bool = a < b;
const x = if (reverse) b else a;
const y = if (reverse) a else b;
// Now do work knowing x and y are ordered versions of a and b.
My reasoning is that this can all be done in CPU registers, whereas actually swapping a and b will probably mean writing the swapped values back to memory. It might get optimised out if the optimiser can see all the scope but, if it can’t, it must play safe and write the swapped values back to memory.