authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2026-08-11 17:48:45-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2026-08-11 17:48:45-07:00
logac8a8d0c5996bbf627438768e3c23154a6404183
tree10d6caa868cf7b9b93cff2dcf680497e8b0a5b00
parent40d88a092514db7bd6ee9d2682a6c64e61798522

langref: caution against using `@hasDecl`


1 files changed, 14 insertions(+), 0 deletions(-)

doc/langref.html.in+14
......@@ -5010,6 +5010,20 @@ fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_val
50105010 <p>Returns whether or not a {#link|Namespace#} has a declaration matching {#syntax#}name{#endsyntax#}.</p>
50115011 {#code|test_hasDecl_builtin.zig#}
50125012
5013 <p>Caution: using {#syntax#}@hasDecl{#endsyntax#} to implement
5014 conditional compilation based on the presence or absence of declarations
5015 in an API runs the risk of introducing dead code into the codebase,
5016 unnoticed. For example, if the field is ever renamed, code which uses
5017 {#syntax#}@hasDecl{#endsyntax#} will compile successfully while failing
5018 to enable or disable an intended block of code. Even a simple a typo in
5019 the field name passed to {#syntax#}@hasDecl{#endsyntax#} would go
5020 unnoticed by the compiler. Thus, it is safer to use alternative methods
5021 to check for the presence or absence of a particular declaration where
5022 possible. For example, if the target operating system would indicate whether a particular
5023 function is available, it more maintainable to check
5024 {#syntax#}@import("builtin").target.os.tag{#endsyntax#} rather than
5025 {#syntax#}@hasDecl{#endsyntax#}.</p>
5026
50135027 {#see_also|@hasField#}
50145028 {#header_close#}
50155029