ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
34.11k stars 2.49k forks source link

Unexpected error when checking if function parameter is a string variable type #20518

Closed alexsch01 closed 2 months ago

alexsch01 commented 3 months ago

Zig Version

0.13.0

Steps to Reproduce and Observed Behavior

const std = @import("std");

pub fn customPrint(x: anytype) void {
    const typeName = @typeName(@TypeOf(x));
    if(
        std.mem.startsWith(u8, typeName, "*const [") and
        std.mem.endsWith(u8, typeName, ":0]u8")
    ) {
        std.debug.print("{s}\n", .{x});
        return;
    }

    std.debug.print("{any}\n", .{x});
}

pub fn main() void {
    customPrint("Hello World");
    customPrint(123);
}

/usr/lib/zig/std/fmt.zig:471:5: error: invalid format string 's' for type 'comptime_int' (exit status 1)

Expected Behavior

Hello World 123

rohlem commented 3 months ago

What is tripping up your code here is the fact that function calls, like std.mem.startsWith and std.mem.endsWith in your if condition, are by default evaluated at runtime, even if all arguments are comptime-known. You have to force comptime evaluation using the comptime unary operator: if (comptime (std.mem.startsWith(u8, typeName, "*const [") and std.mem.endsWith(u8, typeName, ":0]u8"))) { ... } .