检查 zig 数组中是否存在元素

Sim*_*ens 5 zig

有没有更惯用的方法来查找数组中是否包含某个值

fn valueInArray(value: u32, array: []const u32) bool {
    for (array) |num| {
        if (value == num) {
            return true;
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

ex *_*ilo 6

我认为这通常是最惯用的解决方案。可以使用containsAtLeastfrom std.mem,但这似乎是对该函数的滥用(实际上是用于查找序列):

if (std.mem.containsAtLeast(u32, &my_arr, 1, &[_]u32{42})) {
    std.debug.print("Found it!\n", .{});
} else {
    std.debug.print("No secrets found...\n", .{});
}
Run Code Online (Sandbox Code Playgroud)

但我认为OP发布的代码可以通过允许comptime它接受除以下类型之外的类型而变得更加惯用u32

const std = @import("std");

pub fn inSlice(comptime T: type, haystack: []const T, needle: T) bool {
    for (haystack) |thing| {
        if (thing == needle) {
            return true;
        }
    }
    return false;
}

pub fn main() void {
    const my_nums = [_]u32{ 1, 2, 3, 42, 5 };
    const my_chars = [_]u8{ 'a', 'b', 'c', 'X', 'd' };

    // Check for a `u32` in a slice of `u32`:
    if (inSlice(u32, &my_nums, 42)) {
        std.debug.print("Found the secret!\n", .{});
    } else {
        std.debug.print("No secrets found...\n", .{});
    }

    // Check for a `u8` in a slice of `u8`:
    if (inSlice(u8, &my_chars, 'X')) {
        std.debug.print("'X' marks the spot!\n", .{});
    } else {
        std.debug.print("No treasure found...\n", .{});
    }

    // Check for a character in a string:
    if (inSlice(u8, "Marzipan", 'z')) {
        std.debug.print("Found some delicious marzipan!\n", .{});
    } else {
        std.debug.print("No treats for me...\n", .{});
    }
}
Run Code Online (Sandbox Code Playgroud)
if (std.mem.containsAtLeast(u32, &my_arr, 1, &[_]u32{42})) {
    std.debug.print("Found it!\n", .{});
} else {
    std.debug.print("No secrets found...\n", .{});
}
Run Code Online (Sandbox Code Playgroud)