String initialization

hi guys!, would like to ask you guys, so basically I’m using this code to initialize a string and later allocate another slice to it, is this a valid way to do it? the code works but I’m just curious if this is not a good practice. can I still deallocate the struct inside the ArrayList later on or do I need to optionals to initialize the string? any kind of tips and recommendations would help tremendously, thanks!

var default_value: []const u8 = "";
if (start_default <= end_default) {
    default_value = try allocator.dupe(u8, self.script_part[start_default..(end_default + 1)]);
    try states.append(allocator, State.init("", "", "", default_value));
}

I think this should work, because allocator.alloc (and dupe is using alloc) and allocator.free all work as no-ops (operations doing nothing) when the actual length is zero, you shouldn’t have trouble with freeing the memory later on.

5 Likes