by IshKebab · 1y ago · 0 comments
let result = format!("{a}{b}{c}");
In Zig it's something like this: const allocator = std.heap.page_allocator;
const parts = [_][]const u8{"a", "b"};
const result = std.mem.concat(allocator, &parts[0], 2) catch @panic("allocation failure");
defer allocator.free(result);
I dunno if I want to write any really significant programs like that. At least not any that use strings a lot!For wanting to avoid fiddling with multiple repeated alloc/defer-free, it's often convenient to use the arena allocators that allow you to release everything with a single `defer arena.deinit()`
var buffer : [64] u8 = undefined;
const level_name_cstring : stringnt = std.fmt.bufPrintZ(&buffer, "{}. {s}", .{icon_index + 1, level_name}) catch unreachable;
(Make the string "10. Fortress" from the int 10 and "Fortress")The reason is, most of the strings in my game are bounded, and actually, known ahead of time. None of the levels have names that approach anything as long as 64 bytes, so I can actually do a fair bit of string manipulation on the stack before needing to use / save it to an allocator. (At least for now before localization XD)
So it depends on the use case. Sure, string manipulation in general can be tiresome in Zig, but in many cases it's also simple.
This sort of code makes me nervous about Zig.