#Trouble with strings

1 messages · Page 1 of 1 (latest)

eager shore
#

Here is how the type is defined:

pub const YAMLData = union(YAMLDataTag) {
    scalar: union(YAMLScalarTag) {
        integer: i64,
        float: f64,
        string: []u8,
        boolean: bool,
        null: u0,
    },
    sequence: std.ArrayList(YAMLData),
    mapping: std.StringHashMap(YAMLData),
};

and im trying to test it by filling in the string field but i dont know how to get a []u8 at comptime:

test "parse scalar string" {
    try testScalarParse("test", .{ .scalar = .{ .string = "test" } });
}
sage drum
#

use []const u8 if the data can be comptime/constant

eager shore
#

sorry i should expand upon my intended use case

#

for this test i want to define it as a constant but during actual use it will be allocated

#

am i stuck just allocating it for this test

wet fulcrum
#

Even if it's an allocated []u8 you can pass it as []const u8. The way I think of []const u8 is I can't and will not modify the passed memory, it doesn't matter if the original memory is unmodifieable just that because of the type either the function that takes []const u8 or the struct that has it as a field won't be able to modify the memory. which is important static strings cause I believe they will usually be stored in read only memory. The type that would say you can't use runtime a allocated string would be comptime []const u8

eager shore
#

ah okay that makes more sense

#

okay it appears i am a dumbass either way and should just be passing around slices instead of heap allocated strings

sage drum
#

note that I used the word can, you should use []const u8 as long as you're not going to be modifying it