微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 zig 中搜索结构的 ArrayList

如何解决在 zig 中搜索结构的 ArrayList

我希望这是一个关于如何在 zig 中做好这件事的简单答案的问题。

我想搜索某个结构的 ArrayList 以通过其中一个字段查找记录。
在 C++ 中,我会考虑使用 std::find_if 和一个 lambda,但在 zig 标准库中似乎没有这样的东西,除非我错过了什么。

有没有比下面的简单循环更好/更惯用的方法

const std = @import("std");

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

pub fn main() !void {

    const allocator = std.heap.page_allocator;

    var data = std.ArrayList(Person).init(allocator);
    defer data.deinit();

    try data.append(.{.id = 1,.name = "John"});
    try data.append(.{.id = 2,.name = "Dave"});
    try data.append(.{.id = 8,.name = "Bob"});
    try data.append(.{.id = 5,.name = "Steve"});

    // Find the id of the person with name "Bob"
    //
    // -- IS THERE A BETTER WAY IN ZIG THAN THIS LOOP BELOW? --
    //
    var item_index: ?usize = null;
    for (data.items) | person,index | {
        if (std.mem.eql(u8,person.name,"Bob")) {
            item_index = index;
        }
    }

    std.debug.print("Found index is {}\n",.{item_index});


}

解决方法

确实,stdlib 中没有那么多内置实用程序。但是,对于那段代码,您可以将找到的 index 声明为常量:

const item_index = for (data.items) |person,index| {
    if (std.mem.eql(u8,person.name,"Bob")) break index;
} else null;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。