Zig Code Review

Nov 12, 2023

Minimal Zig code review snippets.

const item: MyItem = .{}; // Nope
const item = MyItem{};    // Dope
// Nope
const testing = std.testing;

try testing.expect(false);

// Dope
try std.testing.expect(true);
var buf: [4]u8 = undefined;
const buf_slice = try bufPrint(&buf, "Nope", .{});     // Nope
const buf_slice = try bufPrint(buf[0..], "Dope", .{}); // Dope
std.debug.print("{}", .{int_or_float});  // Nope
std.debug.print("{d}", .{int_or_float}); // Dope
const fld = @as(u8, @intCast(item.fld)); // Nope
const fld: u8 = @intCast(item.fld);      // Dope
for (items) |*item_ptr| {...} // Nope
for (items) |*item| {...}     // Dope
if (maybe_item) |item| {...} // Nope
if (item_opt) |item| {...}   // Dope
while (iter.next()) |item| {...}       // Nope
while (items_iter.next()) |item| {...} // Dope
return MyItem{ .fld = 42 }; // Nope
return .{ .fld = 42 };      // Dope
const Pet = union(enum) {
    cat: union(enum) {
        siberian: void,
        birman: void,
    },
    dog: Dog,
};

const pet = Pet{ .cat = .{ .siberian = {} } }; // Nope
const pet = Pet{ .cat = .siberian };           // Dope
// Nope
for (strs) |*str| str.* = try allocator.alloc(u8, str_len);

// Dope
defer {
    for (strs) |str| allocator.free(str);
    allocator.free(strs);
}
// Nope
if (a > b)
    a = b;
else
    a = 0;

// Dope
a = if (a > b) b else 0;
test "MyItem" {...} // Nope
test MyItem {...}   // Dope
const item_name = @tagName(item_tag);    // Nope
const item_tag_str = @tagName(item_tag); // Dope
return;    // Nope
return {}; // Dope
try std.testing.expectEqual(getItem(), exp_item); // Nope
try std.testing.expectEqual(exp_item, getItem()); // Dope
// Nope
mutex.lock();

runCriticalSection();

mutex.unlock();

// Dope
mutex.lock();
defer mutex.unlock();

runCriticalSection();
// Nope
const Item = struct {
    const Self = @This();

    self_opt: ?*Self = null,
};

// Dope
fn Item(comptime T: type) type {
    return struct {
        const Self = @This();

        self_opt: ?*Self = null,
        fld: T,
    };
}
// Nope
const MyItemKind = enum {
    Extraordinary,
    Ordinary,
};

const MyItem = struct {
    kind: MyItemKind,
};

// Dope
const MyItem = struct {
    const Kind = enum {
        Extraordinary,
        Ordinary,
    };

    kind: Kind,
};
fn allocate(self: MyItem, opts: MyOpts, allocator: std.mem.Allocator) !void {} // Nope
fn allocate(self: MyItem, allocator: std.mem.Allocator, opts: MyOpts) !void {} // Dope
// Nope
const MyItem = struct {
    fld: u8,

    pub fn init() MyItem {
        return .{ fld = 0 };
    }
};

// Dope
const MyItem = struct {
    fld: u8 = 0,
};