2

I just want to create a struct with variable String (utf-8 text).

const Person = struct {
    name: [_]u8, 

};

Is it possible? Or I have to set maximum length of string (e.g. name: [255]u8;)? When I pass to compiler it says:

person.zig:5:12: error: unable to infer array size
    name: [_]u8,

Anyway I miss native String type instead of having to handle with bytes. Is there any library for that?

somenxavier
  • 1,206
  • 3
  • 20
  • 43

1 Answers1

5

You might be looking for a slice type: []u8 or []const u8. A slice type contains a pointer and a length, so the struct does not actually directly hold the string's memory, it is held somewhere else. https://ziglang.org/documentation/0.9.1/#Slices

const Person = struct {
    name: []const u8,
};

Anyway I miss native String type instead of having to handle with bytes. Is there any library for that?

There are some string libraries for zig, but this depends on what features specifically you are looking for. If you are looking for string concatenation and formatting, you can probably use zig's builtin ArrayList

const std = @import("std");

const Person = struct {
    name: std.ArrayList(u8),
};

test "person" {
    const allocator = std.testing.allocator;

    var person: Person = .{
        .name = std.ArrayList(u8).init(allocator),
    };
    defer person.name.deinit();
    try person.name.appendSlice("First ");
    try person.name.appendSlice("Last");
    try person.name.writer().print(". Formatted string: {s}", .{"demo"});

    try std.testing.expectEqualSlices(u8, "First Last. Formatted string: demo", person.name.items);
}

If you are looking for unicode functions like string normalization, you can use a library like Ziglyph

pfg
  • 2,348
  • 1
  • 16
  • 37
  • `name: []const u8,` works but ` name: [] u8,` does not – somenxavier Feb 28 '22 at 19:48
  • 2
    @somenxavier `[]u8` is for a mutable slice of bytes. It doesn't work if you pass a double quoted string to it because those are `[]const u8` and stored in readonly memory in the program's data section. – pfg Feb 28 '22 at 20:45