Opinion Piece: On Zig
blueberrywren.devThe "Debug mode" section does not mention the DebugAllocator[0], which does indeed crash with an error on the "Should be caught!" line. Try this:
const std = @import("std");
pub fn main() !void {
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer _ = gpa.deinit();
const allocator = gpa.allocator();
//const allocator = std.heap.page_allocator;
var buffer = try allocator.alloc(u8, 4);
defer allocator.free(buffer);
buffer[0] = 1;
const new_buffer = try allocator.realloc(buffer, 8);
defer allocator.free(new_buffer);
buffer[0] = 99;
std.debug.print("{}\n", .{buffer[0]});
}
With the page_allocator, it will (incorrectly) print 99. With the DebugAllocator, it will crash with: Segmentation fault at address 0x7f4a78f80000
prog.zig:14:11: 0x1158d55 in main (tmp_9CoXPDDeVU3O2FvW.zig)
buffer[0] = 99;
^
[0] https://ziglang.org/documentation/0.15.1/std/#std.heap.debug...Regarding iteration, a simple solution without reaching for while loops is to iterate on a range and operate relative to the length.
const a = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // 2 4 6 8 10 for (a[0 .. a.len / 2], 0..) |_, i| { std.debug.print("{} ", .{a[i * 2 + 1]}); } std.debug.print("\n", .{}); // 1 3 5 7 9 for (a[0 .. (a.len + 1) / 2], 0..) |_, i| { std.debug.print("{} ", .{a[i * 2]}); } std.debug.print("\n", .{}); // 10 9 8 7 6 5 4 3 2 1 for (0..a.len) |i| { std.debug.print("{} ", .{a[a.len - i - 1]}); }
I don't have enough experience with CPP and/or Clang but Zig compiles its whole build system and stdlib specifically for each project, so in that light I think the Zig compiler is quite fast.
An excellent summary, which I wholeheartedly agree with