Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I tried Zig a bit and found it quite nice, but it is very low level. Like in Rust you concatenate strings like this:

  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!


There's also `std.fmt.allocPrint()` which functions similarly to `format!()`. Although I'd argue its rather poorly named, like many of the functions in the stdlib...

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()`


I would (coming from a C background) guess that `allocPrint()` owes its name from the C standard library function(s) `as(n)printf()`[1]. At least that would make sense, the naming is modernized by being made longer, to gain clarity.

[1]: https://man7.org/linux/man-pages/man3/asprintf.3.html


My game has a bunch of strings, and my string code currently looks very different to this! For example, copying two lines from source:

  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.


Isn't `unreachable` in Zig like in C? So very bad things can happen if you overflow.

This sort of code makes me nervous about Zig.


In safe build modes (ReleaseSafe or Debug) it's an immediate panic, equivalent to calling `.unwrap()` on a None in Rust. In unsafe build modes it's undefined behavior.


Well exactly.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: