5

I expect this is a question with a very simple answer about how to do this well in zig.

I want to search an ArrayList of some struct to find a record by one of the fields.
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.

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


}

1 Answer 1

5

There's not that many built-in utilities present in stdlib, indeed. However, for that piece of code, you may declare the found index as a const:

const item_index = for (data.items) |person, index| {
    if (std.mem.eql(u8, person.name, "Bob")) break index;
} else null;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.