如何处理可变大小的 Zig 结构字符串

问题描述 投票:0回答:1

我有以下内容

const Task = struct {
    id: u32,
    name: [34]u8,
    progress: u8,
};

但是对于

Task.name
声明我有一个问题,那就是名字的长度

我可以将其声明为

    name: [34:0]u8,
但是如何初始化呢?

    name: [34:0]u8 = undefined,
Zig 中是否有
memcpy()
等效项?

或者只是

    name: [34]u8 = undefined,
这只接受 34 字节长的名称

那么,最好的方法是什么(我对动态内存没有太多经验)

string zig
1个回答
0
投票

假设

name
字段应该是一个字符串,通常在 Zig 中您会使用
const u8
的切片作为字符串。然后,您可以根据需要使用字符串文字或动态构建字符串,使用数组或分配器进行存储。像这样的东西:

const std = @import("std");
const print = std.debug.print;

const Task = struct {
    id: u32,
    name: []const u8,
    progress: u8,
};

pub fn main() void {
    const my_task = Task{
        .id = 42,
        .name = "Ultimate Answer",
        .progress = 0,
    };

    print("On the question of \"{s}\"...\n", .{my_task.name});
    print("Universe: {}\n", .{my_task.id});
    print("Humanity: {}\n", .{my_task.progress});

    var another_task = Task{
        .id = 21,
        .name = "",
        .progress = 0,
    };

    print("another_task.name ({s})\n", .{another_task.name});

    another_task.name = "Halfway There!";
    print("another_task.name ({s})\n", .{another_task.name});

    var build_arr = [_]u8{ 'D', 'y', 'n', 'a', 'm', 'i', 'c', '.' };
    build_arr[build_arr.len - 1] = '!';
    another_task.name = build_arr[0..];
    print("another_task.name ({s})\n", .{another_task.name});
}
> zig build-exe .\task.zig
> .\task.exe
On the question of "Ultimate Answer"...
Universe: 42
Humanity: 0
another_task.name ()
another_task.name (Halfway There!)
another_task.name (Dynamic!)

关于

memcpy
,Zig 在标准库中内置了
@memcpy
,以及
std.mem.copyForwards
std.mem.copyBackwards
。何时以及如何使用这些取决于 OP 希望实现的目标的更具体细节。

作为一般规则,人们应该尝试使用切片,如上面的示例代码所示。

© www.soinside.com 2019 - 2024. All rights reserved.