From ac8a8d0c5996bbf627438768e3c23154a6404183 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 11 Aug 2026 17:48:45 -0700 Subject: [PATCH] langref: caution against using `@hasDecl` --- doc/langref.html.in | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/doc/langref.html.in b/doc/langref.html.in index d1c14d15f744c99e4cf6c951bdaed77ac0ba7f3b..0084e01b2e30d0d22ddc233d2fe2aa899fc6b6ed 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -5010,6 +5010,20 @@ fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_val

Returns whether or not a {#link|Namespace#} has a declaration matching {#syntax#}name{#endsyntax#}.

{#code|test_hasDecl_builtin.zig#} +

Caution: using {#syntax#}@hasDecl{#endsyntax#} to implement + conditional compilation based on the presence or absence of declarations + in an API runs the risk of introducing dead code into the codebase, + unnoticed. For example, if the field is ever renamed, code which uses + {#syntax#}@hasDecl{#endsyntax#} will compile successfully while failing + to enable or disable an intended block of code. Even a simple a typo in + the field name passed to {#syntax#}@hasDecl{#endsyntax#} would go + unnoticed by the compiler. Thus, it is safer to use alternative methods + to check for the presence or absence of a particular declaration where + possible. For example, if the target operating system would indicate whether a particular + function is available, it more maintainable to check + {#syntax#}@import("builtin").target.os.tag{#endsyntax#} rather than + {#syntax#}@hasDecl{#endsyntax#}.

+ {#see_also|@hasField#} {#header_close#} -- 2.54.0