Hello again,
after starting my Zig journey some days ago I already wrote some code but now I’m facing a challenge regarding assigning “strings” to a struct field at runtime. As already stated in my previous question coming from Rust it was not necessary to think about such eventually memory related things much.
In general, I have a struct defined in my library which holds some fields containing “strings” ([]const u8). When used at runtime, there is a function which loops over an array of strings using next() method. At every round the current item is assigned to the struct field for some operations. This means in the next turn the next value is (re)assigned to the same field.
What is the most idiomatic way in Zig to handle this?
Take this as example code:
const MyStruct = struct {
field_1: []const u8,
field_2: bool,
fn assignStr(self: *MyStruct, str: []const u8) void {
self.*.field_1 = str;
}
}
// Initialize struct
var my_struct = MyStruct { .field_1 = "", .field_2 = false };
// Some kind of iterator like ArgIterator
var iterator = try std.process.ArgIterator.initWithAllocator(allocator);
// Assigning value to field_1 in struct
while (iterator.next()) |str| {
my_struct.assignStr(str);
// Do some stuff with the field
}
The example is of course strongly simplified (and written freely from my mind and therefore not tested, since I don’t have the opportunity atm) and might not make sense regarding some other aspects of Zig I don’t know much about. Plus, in such a simple example, I know, there is no need for storing the string in a struct field, but in the real code it seems to be correct (I’ll make the repo public and present it in this forum when the code is a little bit more evolved). But I hope the central question is clear.
Since in the case of CLI args the length of the strings can vary, I’m unsure if there is something missing, especially regarding memory management. In Rust thats no big deal, because its handled in the background.
The ArgIterator already allocates memory for the strings it returns. But do I need some other action on those strings when I assign them to the struct field? Or might be a different type better suited when defining the struct (e.g. std.ArrayList(u8))?
Sorry if the solution is very obvious, but as mentioned, I’m still at the beginning and a little bit overwhelmed; but nevertheless already loving it to work with Zig ![]()