我希望这个问题有一个非常简单的答案,关于如何在 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});
}
Run Code Online (Sandbox Code Playgroud)
事实上,stdlib 中并没有那么多内置实用程序。然而,对于那段代码,您可以将 find 声明index为 const:
const item_index = for (data.items) |person, index| {
if (std.mem.eql(u8, person.name, "Bob")) break index;
} else null;
Run Code Online (Sandbox Code Playgroud)