Home > Blockchain >  Create a struct with String parameter
Create a struct with String parameter

Time:03-01

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?

CodePudding user response:

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

  • Related