简体   繁体   English

在 zig 中搜索结构的 ArrayList

[英]Search ArrayList of Structs in zig

I expect this is a question with a very simple answer about how to do this well in zig.我希望这是一个关于如何在 zig 中做好这件事的简单答案的问题。

I want to search an ArrayList of some struct to find a record by one of the fields.我想搜索某个结构的 ArrayList 以通过其中一个字段查找记录。
In C++ I would consider using std::find_if and a lambda but there doesn't seem to be anything like this in the zig standard library unless I missed something.在 C++ 中,我会考虑使用 std::find_if 和 lambda 但在 zig 标准库中似乎没有这样的东西,除非我错过了什么。

Is there a better / more idiomatic way than the simple loop like below?有没有比下面这样的简单循环更好/更惯用的方法?

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});


}

There's not that many built-in utilities present in stdlib, indeed.确实,stdlib 中没有那么多内置实用程序。 However, for that piece of code, you may declare the found index as a const:但是,对于那段代码,您可以将找到的index声明为 const:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM