langref.html.in (349037B) - Raw
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta name="color-scheme" content="light dark"> 7 <title>Documentation - The Zig Programming Language</title> 8 <link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAgklEQVR4AWMYWuD7EllJIM4G4g4g5oIJ/odhOJ8wToOxSTXgNxDHoeiBMfA4+wGShjyYOCkG/IGqWQziEzYAoUAeiF9D5U+DxEg14DRU7jWIT5IBIOdCxf+A+CQZAAoopEB7QJwBCBwHiip8UYmRdrAlDpIMgApwQZNnNii5Dq0MBgCxxycBnwEd+wAAAABJRU5ErkJggg=="> 9 <link rel="icon" href="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNTMgMTQwIj48ZyBmaWxsPSIjRjdBNDFEIj48Zz48cG9seWdvbiBwb2ludHM9IjQ2LDIyIDI4LDQ0IDE5LDMwIi8+PHBvbHlnb24gcG9pbnRzPSI0NiwyMiAzMywzMyAyOCw0NCAyMiw0NCAyMiw5NSAzMSw5NSAyMCwxMDAgMTIsMTE3IDAsMTE3IDAsMjIiIHNoYXBlLXJlbmRlcmluZz0iY3Jpc3BFZGdlcyIvPjxwb2x5Z29uIHBvaW50cz0iMzEsOTUgMTIsMTE3IDQsMTA2Ii8+PC9nPjxnPjxwb2x5Z29uIHBvaW50cz0iNTYsMjIgNjIsMzYgMzcsNDQiLz48cG9seWdvbiBwb2ludHM9IjU2LDIyIDExMSwyMiAxMTEsNDQgMzcsNDQgNTYsMzIiIHNoYXBlLXJlbmRlcmluZz0iY3Jpc3BFZGdlcyIvPjxwb2x5Z29uIHBvaW50cz0iMTE2LDk1IDk3LDExNyA5MCwxMDQiLz48cG9seWdvbiBwb2ludHM9IjExNiw5NSAxMDAsMTA0IDk3LDExNyA0MiwxMTcgNDIsOTUiIHNoYXBlLXJlbmRlcmluZz0iY3Jpc3BFZGdlcyIvPjxwb2x5Z29uIHBvaW50cz0iMTUwLDAgNTIsMTE3IDMsMTQwIDEwMSwyMiIvPjwvZz48Zz48cG9seWdvbiBwb2ludHM9IjE0MSwyMiAxNDAsNDAgMTIyLDQ1Ii8+PHBvbHlnb24gcG9pbnRzPSIxNTMsMjIgMTUzLDExNyAxMDYsMTE3IDEyMCwxMDUgMTI1LDk1IDEzMSw5NSAxMzEsNDUgMTIyLDQ1IDEzMiwzNiAxNDEsMjIiIHNoYXBlLXJlbmRlcmluZz0iY3Jpc3BFZGdlcyIvPjxwb2x5Z29uIHBvaW50cz0iMTI1LDk1IDEzMCwxMTAgMTA2LDExNyIvPjwvZz48L2c+PC9zdmc+"> 10 <style> 11 :root{ 12 --nav-width: 26em; 13 --nav-margin-l: 1em; 14 } 15 body{ 16 font-family: system-ui, -apple-system, Roboto, "Segoe UI", sans-serif; 17 margin: 0; 18 line-height: 1.5; 19 } 20 header { 21 padding: 0 1em; 22 } 23 #contents { 24 max-width: 60em; 25 margin: auto; 26 padding: 0 1em; 27 } 28 #navigation { 29 padding: 0 1em; 30 } 31 table ul { 32 list-style-type: none; 33 padding: 0em; 34 } 35 table li { 36 padding-bottom: 1em; 37 line-height:1.2em; 38 } 39 table, th, td { 40 border-collapse: collapse; 41 border: 1px solid grey; 42 } 43 th, td { 44 padding: 0.5em; 45 } 46 th[scope=row] { 47 text-align: left; 48 font-weight: normal; 49 } 50 51 @media screen and (min-width: 1025px) { 52 header { 53 margin-left: calc(var(--nav-width) + var(--nav-margin-l)); 54 } 55 header h1 { 56 margin: auto; 57 max-width: 30em; 58 } 59 #navigation { 60 overflow: auto; 61 width: var(--nav-width); 62 height: 100vh; 63 position: fixed; 64 top:0; 65 left:0; 66 bottom:0; 67 padding: unset; 68 margin-left: var(--nav-margin-l); 69 } 70 #navigation nav ul { 71 padding-left: 1em; 72 } 73 #contents-wrapper { 74 margin-left: calc(var(--nav-width) + var(--nav-margin-l)); 75 } 76 } 77 78 a:hover,a:focus { 79 background: #fff2a8; 80 } 81 dt { 82 font-weight: bold; 83 } 84 .sgr-1m { 85 font-weight: bold; 86 } 87 .sgr-2m { 88 color: #575757; 89 } 90 .sgr-31_1m { 91 color: #b40000; 92 } 93 .sgr-32_1m { 94 color: green; 95 } 96 .sgr-36_1m { 97 color: #005C7A; 98 } 99 .file { 100 font-weight: bold; 101 border: unset; 102 } 103 code { 104 background: #f8f8f8; 105 border: 1px dotted silver; 106 padding-left: 0.3em; 107 padding-right: 0.3em; 108 } 109 pre > code { 110 display: block; 111 overflow: auto; 112 padding: 0.5em; 113 border: 1px solid #eee; 114 line-height: normal; 115 } 116 samp { 117 background: #fafafa; 118 } 119 pre > samp { 120 display: block; 121 overflow: auto; 122 padding: 0.5em; 123 border: 1px solid #eee; 124 line-height: normal; 125 } 126 kbd { 127 font-weight: normal; 128 } 129 .table-wrapper { 130 width: 100%; 131 overflow-x: auto; 132 } 133 134 .tok-kw { 135 color: #333; 136 font-weight: bold; 137 } 138 .tok-str { 139 color: #d14; 140 } 141 .tok-builtin { 142 color: #005C7A; 143 } 144 .tok-comment { 145 color: #545454; 146 font-style: italic; 147 } 148 .tok-fn { 149 color: #900; 150 font-weight: bold; 151 } 152 .tok-null { 153 color: #005C5C; 154 } 155 .tok-number { 156 color: #005C5C; 157 } 158 .tok-type { 159 color: #458; 160 font-weight: bold; 161 } 162 163 figure { 164 margin: auto 0; 165 } 166 figure pre { 167 margin-top: 0; 168 } 169 170 figcaption { 171 padding-left: 0.5em; 172 font-size: small; 173 border-top-left-radius: 5px; 174 border-top-right-radius: 5px; 175 } 176 figcaption.zig-cap { 177 background: #fcdba5; 178 } 179 figcaption.c-cap { 180 background: #a8b9cc; 181 color: #000; 182 } 183 figcaption.peg-cap { 184 background: #fcdba5; 185 } 186 figcaption.javascript-cap { 187 background: #365d95; 188 color: #fff; 189 } 190 figcaption.shell-cap { 191 background: #ccc; 192 color: #000; 193 } 194 195 aside { 196 border-left: 0.25em solid #f7a41d; 197 padding: 0 1em 0 1em; 198 } 199 200 h1 a, h2 a, h3 a, h4 a, h5 a { 201 text-decoration: none; 202 color: #333; 203 } 204 205 a.hdr { 206 visibility: hidden; 207 } 208 h1:hover > a.hdr, h2:hover > a.hdr, h3:hover > a.hdr, h4:hover > a.hdr, h5:hover > a.hdr { 209 visibility: visible; 210 } 211 212 th pre code { 213 background: none; 214 } 215 216 @media (prefers-color-scheme: dark) { 217 body{ 218 background:#121212; 219 color: #ccc; 220 } 221 a { 222 color: #88f; 223 } 224 a:hover,a:focus { 225 color: #000; 226 } 227 table, th, td { 228 border-color: grey; 229 } 230 .sgr-2m { 231 color: grey; 232 } 233 .sgr-31_1m { 234 color: red; 235 } 236 .sgr-32_1m { 237 color: #00B800; 238 } 239 .sgr-36_1m { 240 color: #0086b3; 241 } 242 code { 243 background: #222; 244 border-color: #444; 245 } 246 pre > code { 247 color: #ccc; 248 background: #222; 249 border: unset; 250 } 251 samp { 252 background: #000; 253 color: #ccc; 254 } 255 pre > samp { 256 border: unset; 257 } 258 .tok-kw { 259 color: #eee; 260 } 261 .tok-str { 262 color: #2e5; 263 } 264 .tok-builtin { 265 color: #ff894c; 266 } 267 .tok-comment { 268 color: #aa7; 269 } 270 .tok-fn { 271 color: #B1A0F8; 272 } 273 .tok-null { 274 color: #ff8080; 275 } 276 .tok-number { 277 color: #ff8080; 278 } 279 .tok-type { 280 color: #68f; 281 } 282 h1 a, h2 a, h3 a, h4 a, h5 a { 283 color: #aaa; 284 } 285 figcaption.zig-cap { 286 background-color: #b27306; 287 color: #000; 288 } 289 figcaption.peg-cap { 290 background-color: #b27306; 291 color: #000; 292 } 293 figcaption.shell-cap { 294 background: #2a2a2a; 295 color: #fff; 296 } 297 } 298 </style> 299 </head> 300 <body> 301 <header><h1>Zig Language Reference</h1></header> 302 <div id="main-wrapper"> 303 <div id="navigation"> 304 <nav aria-labelledby="zig-version"> 305 <h2 id="zig-version">Zig Version</h2> 306 <a href="https://ziglang.org/documentation/0.1.1/">0.1.1</a> | 307 <a href="https://ziglang.org/documentation/0.2.0/">0.2.0</a> | 308 <a href="https://ziglang.org/documentation/0.3.0/">0.3.0</a> | 309 <a href="https://ziglang.org/documentation/0.4.0/">0.4.0</a> | 310 <a href="https://ziglang.org/documentation/0.5.0/">0.5.0</a> | 311 <a href="https://ziglang.org/documentation/0.6.0/">0.6.0</a> | 312 <a href="https://ziglang.org/documentation/0.7.1/">0.7.1</a> | 313 <a href="https://ziglang.org/documentation/0.8.1/">0.8.1</a> | 314 <a href="https://ziglang.org/documentation/0.9.1/">0.9.1</a> | 315 <a href="https://ziglang.org/documentation/0.10.1/">0.10.1</a> | 316 <a href="https://ziglang.org/documentation/0.11.0/">0.11.0</a> | 317 <a href="https://ziglang.org/documentation/0.12.0/">0.12.0</a> | 318 <a href="https://ziglang.org/documentation/0.13.0/">0.13.0</a> | 319 <a href="https://ziglang.org/documentation/0.14.1/">0.14.1</a> | 320 <a href="https://ziglang.org/documentation/0.15.2/">0.15.2</a> | 321 master 322 </nav> 323 <nav aria-labelledby="table-of-contents"> 324 <h2 id="table-of-contents">Table of Contents</h2> 325 {#nav#} 326 </nav> 327 </div> 328 <div id="contents-wrapper"><main id="contents"> 329 {#header_open|Introduction#} 330 <p> 331 <a href="https://ziglang.org">Zig</a> is a general-purpose programming language and toolchain for maintaining 332 <strong>robust</strong>, <strong>optimal</strong>, and <strong>reusable</strong> software. 333 </p> 334 <dl> 335 <dt>Robust</dt><dd>Behavior is correct even for edge cases such as out of memory.</dd> 336 <dt>Optimal</dt><dd>Write programs the best way they can behave and perform.</dd> 337 <dt>Reusable</dt><dd>The same code works in many environments which have different 338 constraints.</dd> 339 <dt>Maintainable</dt><dd>Precisely communicate intent to the compiler and 340 other programmers. The language imposes a low overhead to reading code and is 341 resilient to changing requirements and environments.</dd> 342 </dl> 343 <p> 344 Often the most efficient way to learn something new is to see examples, so 345 this documentation shows how to use each of Zig's features. It is 346 all on one page so you can search with your browser's search tool. 347 </p> 348 <p> 349 The code samples in this document are compiled and tested as part of the main test suite of Zig. 350 </p> 351 <p> 352 This HTML document depends on no external files, so you can use it offline. 353 </p> 354 {#header_close#} 355 356 {#header_open|Zig Standard Library#} 357 <p> 358 The <a href="https://ziglang.org/documentation/master/std/">Zig Standard Library</a> has its own documentation. 359 </p> 360 <p> 361 Zig's Standard Library contains commonly used algorithms, data structures, and definitions to help you build programs or libraries. 362 You will see many examples of Zig's Standard Library used in this documentation. To learn more about the Zig Standard Library, 363 visit the link above. 364 </p> 365 <p> 366 Alternatively, the Zig Standard Library documentation is provided with each Zig distribution. It can be rendered via a local webserver with: 367 </p> 368 {#shell_samp#}zig std{#end_shell_samp#} 369 {#header_close#} 370 371 {#header_open|Hello World#} 372 373 {#code|hello.zig#} 374 375 <p> 376 Most of the time, it is more appropriate to write to stderr rather than stdout, and 377 whether or not the message is successfully written to the stream is irrelevant. 378 Also, formatted printing often comes in handy. For this common case, 379 there is a simpler API: 380 </p> 381 {#code|hello_again.zig#} 382 383 <p> 384 In this case, the {#syntax#}!{#endsyntax#} may be omitted from the return 385 type of <code>main</code> because no errors are returned from the function. 386 </p> 387 {#see_also|Values|Tuples|@import|Errors|Entry Point|Source Encoding|try#} 388 {#header_close#} 389 {#header_open|Comments#} 390 <p> 391 Zig supports 3 types of comments. Normal comments are ignored, but doc comments 392 and top-level doc comments are used by the compiler to generate the package documentation. 393 </p> 394 <p> 395 The generated documentation is still experimental, and can be produced with: 396 </p> 397 {#shell_samp#}zig test -femit-docs main.zig{#end_shell_samp#} 398 {#code|comments.zig#} 399 400 <p> 401 There are no multiline comments in Zig (e.g. like <code class="c">/* */</code> 402 comments in C). This allows Zig to have the property that each line 403 of code can be tokenized out of context. 404 </p> 405 {#header_open|Doc Comments#} 406 <p> 407 A doc comment is one that begins with exactly three slashes (i.e. 408 {#syntax#}///{#endsyntax#} but not {#syntax#}////{#endsyntax#}); 409 multiple doc comments in a row are merged together to form a multiline 410 doc comment. The doc comment documents whatever immediately follows it. 411 </p> 412 {#code|doc_comments.zig#} 413 414 <p> 415 Doc comments are only allowed in certain places; it is a compile error to 416 have a doc comment in an unexpected place, such as in the middle of an expression, 417 or just before a non-doc comment. 418 </p> 419 {#code|invalid_doc-comment.zig#} 420 421 {#code|unattached_doc-comment.zig#} 422 423 <p> 424 Doc comments can be interleaved with normal comments. Currently, when producing 425 the package documentation, normal comments are merged with doc comments. 426 </p> 427 {#header_close#} 428 {#header_open|Top-Level Doc Comments#} 429 <p> 430 A top-level doc comment is one that begins with two slashes and an exclamation 431 point: {#syntax#}//!{#endsyntax#}; it documents the current module. 432 </p> 433 <p> 434 It is a compile error if a top-level doc comment is not placed at the start 435 of a {#link|container|Containers#}, before any expressions. 436 </p> 437 {#code|tldoc_comments.zig#} 438 439 {#header_close#} 440 {#header_close#} 441 {#header_open|Values#} 442 {#code|values.zig#} 443 444 {#header_open|Primitive Types#} 445 <div class="table-wrapper"> 446 <table> 447 <caption>Primitive Types</caption> 448 <thead> 449 <tr> 450 <th scope="col">Type</th> 451 <th scope="col">C Equivalent</th> 452 <th scope="col">Description</th> 453 </tr> 454 </thead> 455 <tbody> 456 <tr> 457 <th scope="row">{#syntax#}i8{#endsyntax#}</th> 458 <td><code class="c">int8_t</code></td> 459 <td>signed 8-bit integer</td> 460 </tr> 461 <tr> 462 <th scope="row">{#syntax#}u8{#endsyntax#}</th> 463 <td><code class="c">uint8_t</code></td> 464 <td>unsigned 8-bit integer</td> 465 </tr> 466 <tr> 467 <th scope="row">{#syntax#}i16{#endsyntax#}</th> 468 <td><code class="c">int16_t</code></td> 469 <td>signed 16-bit integer</td> 470 </tr> 471 <tr> 472 <th scope="row">{#syntax#}u16{#endsyntax#}</th> 473 <td><code class="c">uint16_t</code></td> 474 <td>unsigned 16-bit integer</td> 475 </tr> 476 <tr> 477 <th scope="row">{#syntax#}i32{#endsyntax#}</th> 478 <td><code class="c">int32_t</code></td> 479 <td>signed 32-bit integer</td> 480 </tr> 481 <tr> 482 <th scope="row">{#syntax#}u32{#endsyntax#}</th> 483 <td><code class="c">uint32_t</code></td> 484 <td>unsigned 32-bit integer</td> 485 </tr> 486 <tr> 487 <th scope="row">{#syntax#}i64{#endsyntax#}</th> 488 <td><code class="c">int64_t</code></td> 489 <td>signed 64-bit integer</td> 490 </tr> 491 <tr> 492 <th scope="row">{#syntax#}u64{#endsyntax#}</th> 493 <td><code class="c">uint64_t</code></td> 494 <td>unsigned 64-bit integer</td> 495 </tr> 496 <tr> 497 <th scope="row">{#syntax#}i128{#endsyntax#}</th> 498 <td><code class="c">__int128</code></td> 499 <td>signed 128-bit integer</td> 500 </tr> 501 <tr> 502 <th scope="row">{#syntax#}u128{#endsyntax#}</th> 503 <td><code class="c">unsigned __int128</code></td> 504 <td>unsigned 128-bit integer</td> 505 </tr> 506 <tr> 507 <th scope="row">{#syntax#}isize{#endsyntax#}</th> 508 <td><code class="c">intptr_t</code></td> 509 <td>signed pointer sized integer</td> 510 </tr> 511 <tr> 512 <th scope="row">{#syntax#}usize{#endsyntax#}</th> 513 <td><code class="c">uintptr_t</code>, <code class="c">size_t</code></td> 514 <td>unsigned pointer sized integer. Also see <a href="https://github.com/ziglang/zig/issues/5185">#5185</a></td> 515 </tr> 516 517 <tr> 518 <th scope="row">{#syntax#}c_char{#endsyntax#}</th> 519 <td><code class="c">char</code></td> 520 <td>for ABI compatibility with C</td> 521 </tr> 522 <tr> 523 <th scope="row">{#syntax#}c_short{#endsyntax#}</th> 524 <td><code class="c">short</code></td> 525 <td>for ABI compatibility with C</td> 526 </tr> 527 <tr> 528 <th scope="row">{#syntax#}c_ushort{#endsyntax#}</th> 529 <td><code class="c">unsigned short</code></td> 530 <td>for ABI compatibility with C</td> 531 </tr> 532 <tr> 533 <th scope="row">{#syntax#}c_int{#endsyntax#}</th> 534 <td><code class="c">int</code></td> 535 <td>for ABI compatibility with C</td> 536 </tr> 537 <tr> 538 <th scope="row">{#syntax#}c_uint{#endsyntax#}</th> 539 <td><code class="c">unsigned int</code></td> 540 <td>for ABI compatibility with C</td> 541 </tr> 542 <tr> 543 <th scope="row">{#syntax#}c_long{#endsyntax#}</th> 544 <td><code class="c">long</code></td> 545 <td>for ABI compatibility with C</td> 546 </tr> 547 <tr> 548 <th scope="row">{#syntax#}c_ulong{#endsyntax#}</th> 549 <td><code class="c">unsigned long</code></td> 550 <td>for ABI compatibility with C</td> 551 </tr> 552 <tr> 553 <th scope="row">{#syntax#}c_longlong{#endsyntax#}</th> 554 <td><code class="c">long long</code></td> 555 <td>for ABI compatibility with C</td> 556 </tr> 557 <tr> 558 <th scope="row">{#syntax#}c_ulonglong{#endsyntax#}</th> 559 <td><code class="c">unsigned long long</code></td> 560 <td>for ABI compatibility with C</td> 561 </tr> 562 <tr> 563 <th scope="row">{#syntax#}c_longdouble{#endsyntax#}</th> 564 <td><code class="c">long double</code></td> 565 <td>for ABI compatibility with C</td> 566 </tr> 567 568 <tr> 569 <th scope="row">{#syntax#}f16{#endsyntax#}</th> 570 <td><code class="c">_Float16</code></td> 571 <td>16-bit floating point (10-bit mantissa) IEEE-754-2008 binary16</td> 572 </tr> 573 <tr> 574 <th scope="row">{#syntax#}f32{#endsyntax#}</th> 575 <td><code class="c">float</code></td> 576 <td>32-bit floating point (23-bit mantissa) IEEE-754-2008 binary32</td> 577 </tr> 578 <tr> 579 <th scope="row">{#syntax#}f64{#endsyntax#}</th> 580 <td><code class="c">double</code></td> 581 <td>64-bit floating point (52-bit mantissa) IEEE-754-2008 binary64</td> 582 </tr> 583 <tr> 584 <th scope="row">{#syntax#}f80{#endsyntax#}</th> 585 <td><code class="c">long double</code></td> 586 <td>80-bit floating point (64-bit mantissa) IEEE-754-2008 80-bit extended precision</td> 587 </tr> 588 <tr> 589 <th scope="row">{#syntax#}f128{#endsyntax#}</th> 590 <td><code class="c">_Float128</code></td> 591 <td>128-bit floating point (112-bit mantissa) IEEE-754-2008 binary128</td> 592 </tr> 593 <tr> 594 <th scope="row">{#syntax#}bool{#endsyntax#}</th> 595 <td><code class="c">bool</code></td> 596 <td>{#syntax#}true{#endsyntax#} or {#syntax#}false{#endsyntax#}</td> 597 </tr> 598 <tr> 599 <th scope="row">{#syntax#}anyopaque{#endsyntax#}</th> 600 <td><code class="c">void</code></td> 601 <td>Used for type-erased pointers.</td> 602 </tr> 603 <tr> 604 <th scope="row">{#syntax#}void{#endsyntax#}</th> 605 <td>(none)</td> 606 <td>Always the value {#syntax#}void{}{#endsyntax#}</td> 607 </tr> 608 <tr> 609 <th scope="row">{#syntax#}noreturn{#endsyntax#}</th> 610 <td>(none)</td> 611 <td>the type of {#syntax#}break{#endsyntax#}, {#syntax#}continue{#endsyntax#}, {#syntax#}return{#endsyntax#}, {#syntax#}unreachable{#endsyntax#}, and {#syntax#}while (true) {}{#endsyntax#}</td> 612 </tr> 613 <tr> 614 <th scope="row">{#syntax#}type{#endsyntax#}</th> 615 <td>(none)</td> 616 <td>the type of types</td> 617 </tr> 618 <tr> 619 <th scope="row">{#syntax#}anyerror{#endsyntax#}</th> 620 <td>(none)</td> 621 <td>an error code</td> 622 </tr> 623 <tr> 624 <th scope="row">{#syntax#}comptime_int{#endsyntax#}</th> 625 <td>(none)</td> 626 <td>Only allowed for {#link|comptime#}-known values. The type of integer literals.</td> 627 </tr> 628 <tr> 629 <th scope="row">{#syntax#}comptime_float{#endsyntax#}</th> 630 <td>(none)</td> 631 <td>Only allowed for {#link|comptime#}-known values. The type of float literals.</td> 632 </tr> 633 </tbody> 634 </table> 635 </div> 636 <p> 637 In addition to the integer types above, arbitrary bit-width integers can be referenced by using 638 an identifier of <code>i</code> or <code>u</code> followed by digits. For example, the identifier 639 {#syntax#}i7{#endsyntax#} refers to a signed 7-bit integer. The maximum allowed bit-width of an 640 integer type is {#syntax#}65535{#endsyntax#}. 641 </p> 642 {#see_also|Integers|Floats|void|Errors|@Type#} 643 {#header_close#} 644 {#header_open|Primitive Values#} 645 <div class="table-wrapper"> 646 <table> 647 <caption>Primitive Values</caption> 648 <thead> 649 <tr> 650 <th scope="col">Name</th> 651 <th scope="col">Description</th> 652 </tr> 653 </thead> 654 <tbody> 655 <tr> 656 <th scope="row">{#syntax#}true{#endsyntax#} and {#syntax#}false{#endsyntax#}</th> 657 <td>{#syntax#}bool{#endsyntax#} values</td> 658 </tr> 659 <tr> 660 <th scope="row">{#syntax#}null{#endsyntax#}</th> 661 <td>used to set an optional type to {#syntax#}null{#endsyntax#}</td> 662 </tr> 663 <tr> 664 <th scope="row">{#syntax#}undefined{#endsyntax#}</th> 665 <td>used to leave a value unspecified</td> 666 </tr> 667 </tbody> 668 </table> 669 </div> 670 {#see_also|Optionals|undefined#} 671 {#header_close#} 672 {#header_open|String Literals and Unicode Code Point Literals#} 673 <p> 674 String literals are constant single-item {#link|Pointers#} to null-terminated byte arrays. 675 The type of string literals encodes both the length, and the fact that they are null-terminated, 676 and thus they can be {#link|coerced|Type Coercion#} to both {#link|Slices#} and 677 {#link|Null-Terminated Pointers|Sentinel-Terminated Pointers#}. 678 Dereferencing string literals converts them to {#link|Arrays#}. 679 </p> 680 <p> 681 Because Zig source code is {#link|UTF-8 encoded|Source Encoding#}, any 682 non-ASCII bytes appearing within a string literal in source code carry 683 their UTF-8 meaning into the content of the string in the Zig program; 684 the bytes are not modified by the compiler. It is possible to embed 685 non-UTF-8 bytes into a string literal using <code>\xNN</code> notation. 686 </p> 687 <p>Indexing into a string containing non-ASCII bytes returns individual 688 bytes, whether valid UTF-8 or not.</p> 689 <p> 690 Unicode code point literals have type {#syntax#}comptime_int{#endsyntax#}, the same as 691 {#link|Integer Literals#}. All {#link|Escape Sequences#} are valid in both string literals 692 and Unicode code point literals. 693 </p> 694 {#code|string_literals.zig#} 695 696 {#see_also|Arrays|Source Encoding#} 697 {#header_open|Escape Sequences#} 698 <div class="table-wrapper"> 699 <table> 700 <caption>Escape Sequences</caption> 701 <thead> 702 <tr> 703 <th scope="col">Escape Sequence</th> 704 <th scope="col">Name</th> 705 </tr> 706 </thead> 707 <tbody> 708 <tr> 709 <th scope="row"><code>\n</code></th> 710 <td>Newline</td> 711 </tr> 712 <tr> 713 <th scope="row"><code>\r</code></th> 714 <td>Carriage Return</td> 715 </tr> 716 <tr> 717 <th scope="row"><code>\t</code></th> 718 <td>Tab</td> 719 </tr> 720 <tr> 721 <th scope="row"><code>\\</code></th> 722 <td>Backslash</td> 723 </tr> 724 <tr> 725 <th scope="row"><code>\'</code></th> 726 <td>Single Quote</td> 727 </tr> 728 <tr> 729 <th scope="row"><code>\"</code></th> 730 <td>Double Quote</td> 731 </tr> 732 <tr> 733 <th scope="row"><code>\xNN</code></th> 734 <td>hexadecimal 8-bit byte value (2 digits)</td> 735 </tr> 736 <tr> 737 <th scope="row"><code>\u{NNNNNN}</code></th> 738 <td>hexadecimal Unicode scalar value UTF-8 encoded (1 or more digits)</td> 739 </tr> 740 </tbody> 741 </table> 742 </div> 743 <p>Note that the maximum valid Unicode scalar value is {#syntax#}0x10ffff{#endsyntax#}.</p> 744 {#header_close#} 745 {#header_open|Multiline String Literals#} 746 <p> 747 Multiline string literals have no escapes and can span across multiple lines. 748 To start a multiline string literal, use the {#syntax#}\\{#endsyntax#} token. Just like a comment, 749 the string literal goes until the end of the line. The end of the line is 750 not included in the string literal. 751 However, if the next line begins with {#syntax#}\\{#endsyntax#} then a newline is appended and 752 the string literal continues. 753 </p> 754 {#code|multiline_string_literals.zig#} 755 756 {#see_also|@embedFile#} 757 {#header_close#} 758 {#header_close#} 759 {#header_open|Assignment#} 760 <p>Use the {#syntax#}const{#endsyntax#} keyword to assign a value to an identifier:</p> 761 {#code|constant_identifier_cannot_change.zig#} 762 763 <p>{#syntax#}const{#endsyntax#} applies to all of the bytes that the identifier immediately addresses. {#link|Pointers#} have their own const-ness.</p> 764 <p>If you need a variable that you can modify, use the {#syntax#}var{#endsyntax#} keyword:</p> 765 {#code|mutable_var.zig#} 766 767 <p>Variables must be initialized:</p> 768 {#code|var_must_be_initialized.zig#} 769 770 {#header_open|undefined#} 771 <p>Use {#syntax#}undefined{#endsyntax#} to leave variables uninitialized:</p> 772 {#code|assign_undefined.zig#} 773 774 <p> 775 {#syntax#}undefined{#endsyntax#} can be {#link|coerced|Type Coercion#} to any type. 776 Once this happens, it is no longer possible to detect that the value is {#syntax#}undefined{#endsyntax#}. 777 {#syntax#}undefined{#endsyntax#} means the value could be anything, even something that is nonsense 778 according to the type. Translated into English, {#syntax#}undefined{#endsyntax#} means "Not a meaningful 779 value. Using this value would be a bug. The value will be unused, or overwritten before being used." 780 </p> 781 <p> 782 In {#link|Debug#} and {#link|ReleaseSafe#} mode, Zig writes {#syntax#}0xaa{#endsyntax#} bytes to undefined memory. This is to catch 783 bugs early, and to help detect use of undefined memory in a debugger. However, this behavior is only an 784 implementation feature, not a language semantic, so it is not guaranteed to be observable to code. 785 </p> 786 {#header_close#} 787 788 {#header_open|Destructuring#} 789 <p> 790 A destructuring assignment can separate elements of indexable aggregate types 791 ({#link|Tuples#}, {#link|Arrays#}, {#link|Vectors#}): 792 </p> 793 {#code|destructuring_to_existing.zig#} 794 795 <p> 796 A destructuring expression may only appear within a block (i.e. not at container scope). 797 The left hand side of the assignment must consist of a comma separated list, 798 each element of which may be either an lvalue (for instance, an existing `var`) or a variable declaration: 799 </p> 800 {#code|destructuring_mixed.zig#} 801 802 <p> 803 A destructure may be prefixed with the {#syntax#}comptime{#endsyntax#} keyword, in which case the entire 804 destructure expression is evaluated at {#link|comptime#}. All {#syntax#}var{#endsyntax#}s declared would 805 be {#syntax#}comptime var{#endsyntax#}s and all expressions (both result locations and the assignee 806 expression) are evaluated at {#link|comptime#}. 807 </p> 808 809 {#see_also|Destructuring Tuples|Destructuring Arrays|Destructuring Vectors#} 810 {#header_close#} 811 {#header_close#} 812 {#header_close#} 813 {#header_open|Zig Test#} 814 <p> 815 Code written within one or more {#syntax#}test{#endsyntax#} declarations can be used to ensure behavior meets expectations: 816 </p> 817 {#code|testing_introduction.zig#} 818 819 <p> 820 The <code class="file">testing_introduction.zig</code> code sample tests the {#link|function|Functions#} 821 {#syntax#}addOne{#endsyntax#} to ensure that it returns {#syntax#}42{#endsyntax#} given the input 822 {#syntax#}41{#endsyntax#}. From this test's perspective, the {#syntax#}addOne{#endsyntax#} function is 823 said to be <em>code under test</em>. 824 </p> 825 <p> 826 <kbd>zig test</kbd> is a tool that creates and runs a test build. By default, it builds and runs an 827 executable program using the <em>default test runner</em> provided by the {#link|Zig Standard Library#} 828 as its main entry point. During the build, {#syntax#}test{#endsyntax#} declarations found while 829 {#link|resolving|File and Declaration Discovery#} the given Zig source file are included for the default test runner 830 to run and report on. 831 </p> 832 <aside> 833 This documentation discusses the features of the default test runner as provided by the Zig Standard Library. 834 Its source code is located in <code class="file">lib/compiler/test_runner.zig</code>. 835 </aside> 836 <p> 837 The shell output shown above displays two lines after the <kbd>zig test</kbd> command. These lines are 838 printed to standard error by the default test runner: 839 </p> 840 <dl> 841 <dt><samp>1/2 testing_introduction.test.expect addOne adds one to 41...</samp></dt> 842 <dd>Lines like this indicate which test, out of the total number of tests, is being run. 843 In this case, <samp>1/2</samp> indicates that the first test, out of a total of two tests, 844 is being run. Note that, when the test runner program's standard error is output 845 to the terminal, these lines are cleared when a test succeeds. 846 </dd> 847 <dt><samp>2/2 testing_introduction.decltest.addOne...</samp></dt> 848 <dd>When the test name is an identifier, the default test runner uses the text 849 decltest instead of test. 850 </dd> 851 <dt><samp>All 2 tests passed.</samp></dt> 852 <dd>This line indicates the total number of tests that have passed.</dd> 853 </dl> 854 {#header_open|Test Declarations#} 855 <p> 856 Test declarations contain the {#link|keyword|Keyword Reference#} {#syntax#}test{#endsyntax#}, followed by an 857 optional name written as a {#link|string literal|String Literals and Unicode Code Point Literals#} or an 858 {#link|identifier|Identifiers#}, followed by a {#link|block|Blocks#} containing any valid Zig code that 859 is allowed in a {#link|function|Functions#}. 860 </p> 861 <p>Non-named test blocks always run during test builds and are exempt from 862 {#link|Skip Tests#}.</p> 863 <p> 864 Test declarations are similar to {#link|Functions#}: they have a return type and a block of code. The implicit 865 return type of {#syntax#}test{#endsyntax#} is the {#link|Error Union Type#} {#syntax#}anyerror!void{#endsyntax#}, 866 and it cannot be changed. When a Zig source file is not built using the <kbd>zig test</kbd> tool, the test 867 declarations are omitted from the build. 868 </p> 869 <p> 870 Test declarations can be written in the same file, where code under test is written, or in a separate Zig source file. 871 Since test declarations are top-level declarations, they are order-independent and can 872 be written before or after the code under test. 873 </p> 874 {#see_also|The Global Error Set|Grammar#} 875 {#header_open|Doctests#} 876 <p> 877 Test declarations named using an identifier are <em>doctests</em>. The identifier must refer to another declaration in 878 scope. A doctest, like a {#link|doc comment|Doc Comments#}, serves as documentation for the associated declaration, and 879 will appear in the generated documentation for the declaration. 880 </p> 881 <p> 882 An effective doctest should be self-contained and focused on the declaration being tested, answering questions a new 883 user might have about its interface or intended usage, while avoiding unnecessary or confusing details. A doctest is not 884 a substitute for a doc comment, but rather a supplement and companion providing a testable, code-driven example, verified 885 by <kbd>zig test</kbd>. 886 </p> 887 {#header_close#} 888 {#header_close#} 889 {#header_open|Test Failure#} 890 <p> 891 The default test runner checks for an {#link|error|Errors#} returned from a test. 892 When a test returns an error, the test is considered a failure and its {#link|error return trace|Error Return Traces#} 893 is output to standard error. The total number of failures will be reported after all tests have run. 894 </p> 895 {#code|testing_failure.zig#} 896 897 {#header_close#} 898 {#header_open|Skip Tests#} 899 <p> 900 One way to skip tests is to filter them out by using the <kbd>zig test</kbd> command line parameter 901 <kbd>--test-filter [text]</kbd>. This makes the test build only include tests whose name contains the 902 supplied filter text. Note that non-named tests are run even when using the <kbd>--test-filter [text]</kbd> 903 command line parameter. 904 </p> 905 <p> 906 To programmatically skip a test, make a {#syntax#}test{#endsyntax#} return the error 907 {#syntax#}error.SkipZigTest{#endsyntax#} and the default test runner will consider the test as being skipped. 908 The total number of skipped tests will be reported after all tests have run. 909 </p> 910 {#code|testing_skip.zig#} 911 912 {#header_close#} 913 914 {#header_open|Report Memory Leaks#} 915 <p> 916 When code allocates {#link|Memory#} using the {#link|Zig Standard Library#}'s testing allocator, 917 {#syntax#}std.testing.allocator{#endsyntax#}, the default test runner will report any leaks that are 918 found from using the testing allocator: 919 </p> 920 {#code|testing_detect_leak.zig#} 921 922 {#see_also|defer|Memory#} 923 {#header_close#} 924 {#header_open|Detecting Test Build#} 925 <p> 926 Use the {#link|compile variable|Compile Variables#} {#syntax#}@import("builtin").is_test{#endsyntax#} 927 to detect a test build: 928 </p> 929 {#code|testing_detect_test.zig#} 930 931 {#header_close#} 932 {#header_open|Test Output and Logging#} 933 <p> 934 The default test runner and the Zig Standard Library's testing namespace output messages to standard error. 935 </p> 936 {#header_close#} 937 {#header_open|The Testing Namespace#} 938 <p> 939 The Zig Standard Library's <code>testing</code> namespace contains useful functions to help 940 you create tests. In addition to the <code>expect</code> function, this document uses a couple of more functions 941 as exemplified here: 942 </p> 943 {#code|testing_namespace.zig#} 944 945 <p>The Zig Standard Library also contains functions to compare {#link|Slices#}, strings, and more. See the rest of the 946 {#syntax#}std.testing{#endsyntax#} namespace in the {#link|Zig Standard Library#} for more available functions.</p> 947 {#header_close#} 948 {#header_open|Test Tool Documentation#} 949 <p> 950 <kbd>zig test</kbd> has a few command line parameters which affect the compilation. 951 See <kbd>zig test --help</kbd> for a full list. 952 </p> 953 {#header_close#} 954 {#header_close#} 955 956 {#header_open|Variables#} 957 <p> 958 A variable is a unit of {#link|Memory#} storage. 959 </p> 960 <p> 961 It is generally preferable to use {#syntax#}const{#endsyntax#} rather than 962 {#syntax#}var{#endsyntax#} when declaring a variable. This causes less work for both 963 humans and computers to do when reading code, and creates more optimization opportunities. 964 </p> 965 <p> 966 The {#syntax#}extern{#endsyntax#} keyword or {#link|@extern#} builtin function can be used to link against a variable that is exported 967 from another object. The {#syntax#}export{#endsyntax#} keyword or {#link|@export#} builtin function 968 can be used to make a variable available to other objects at link time. In both cases, 969 the type of the variable must be C ABI compatible. 970 </p> 971 {#see_also|Exporting a C Library#} 972 973 {#header_open|Identifiers#} 974 <p> 975 Variable identifiers are never allowed to shadow identifiers from an outer scope. 976 </p> 977 <p> 978 Identifiers must start with an alphabetic character or underscore and may be followed 979 by any number of alphanumeric characters or underscores. 980 They must not overlap with any keywords. See {#link|Keyword Reference#}. 981 </p> 982 <p> 983 If a name that does not fit these requirements is needed, such as for linking with external libraries, the {#syntax#}@""{#endsyntax#} syntax may be used. 984 </p> 985 {#code|identifiers.zig#} 986 987 {#header_close#} 988 989 {#header_open|Container Level Variables#} 990 <p> 991 {#link|Container|Containers#} level variables have static lifetime and are order-independent and lazily analyzed. 992 The initialization value of container level variables is implicitly 993 {#link|comptime#}. If a container level variable is {#syntax#}const{#endsyntax#} then its value is 994 {#syntax#}comptime{#endsyntax#}-known, otherwise it is runtime-known. 995 </p> 996 {#code|test_container_level_variables.zig#} 997 998 <p> 999 Container level variables may be declared inside a {#link|struct#}, {#link|union#}, {#link|enum#}, or {#link|opaque#}: 1000 </p> 1001 {#code|test_namespaced_container_level_variable.zig#} 1002 1003 {#header_close#} 1004 1005 {#header_open|Static Local Variables#} 1006 <p> 1007 It is also possible to have local variables with static lifetime by using containers inside functions. 1008 </p> 1009 {#code|test_static_local_variable.zig#} 1010 1011 {#header_close#} 1012 1013 {#header_open|Thread Local Variables#} 1014 <p>A variable may be specified to be a thread-local variable using the 1015 {#syntax#}threadlocal{#endsyntax#} keyword, 1016 which makes each thread work with a separate instance of the variable:</p> 1017 {#code|test_thread_local_variables.zig#} 1018 1019 <p> 1020 For {#link|Single Threaded Builds#}, all thread local variables are treated as regular {#link|Container Level Variables#}. 1021 </p> 1022 <p> 1023 Thread local variables may not be {#syntax#}const{#endsyntax#}. 1024 </p> 1025 {#header_close#} 1026 1027 {#header_open|Local Variables#} 1028 <p> 1029 Local variables occur inside {#link|Functions#}, {#link|comptime#} blocks, and {#link|@cImport#} blocks. 1030 </p> 1031 <p> 1032 When a local variable is {#syntax#}const{#endsyntax#}, it means that after initialization, the variable's 1033 value will not change. If the initialization value of a {#syntax#}const{#endsyntax#} variable is 1034 {#link|comptime#}-known, then the variable is also {#syntax#}comptime{#endsyntax#}-known. 1035 </p> 1036 <p> 1037 A local variable may be qualified with the {#syntax#}comptime{#endsyntax#} keyword. This causes 1038 the variable's value to be {#syntax#}comptime{#endsyntax#}-known, and all loads and stores of the 1039 variable to happen during semantic analysis of the program, rather than at runtime. 1040 All variables declared in a {#syntax#}comptime{#endsyntax#} expression are implicitly 1041 {#syntax#}comptime{#endsyntax#} variables. 1042 </p> 1043 {#code|test_comptime_variables.zig#} 1044 1045 {#header_close#} 1046 {#header_close#} 1047 1048 {#header_open|Integers#} 1049 {#header_open|Integer Literals#} 1050 {#code|integer_literals.zig#} 1051 1052 {#header_close#} 1053 {#header_open|Runtime Integer Values#} 1054 <p> 1055 Integer literals have no size limitation, and if any Illegal Behavior occurs, 1056 the compiler catches it. 1057 </p> 1058 <p> 1059 However, once an integer value is no longer known at compile-time, it must have a 1060 known size, and is vulnerable to safety-checked {#link|Illegal Behavior#}. 1061 </p> 1062 {#code|runtime_vs_comptime.zig#} 1063 1064 <p> 1065 In this function, values {#syntax#}a{#endsyntax#} and {#syntax#}b{#endsyntax#} are known only at runtime, 1066 and thus this division operation is vulnerable to both {#link|Integer Overflow#} and 1067 {#link|Division by Zero#}. 1068 </p> 1069 <p> 1070 Operators such as {#syntax#}+{#endsyntax#} and {#syntax#}-{#endsyntax#} cause {#link|Illegal Behavior#} on 1071 integer overflow. Alternative operators are provided for wrapping and saturating arithmetic on all targets. 1072 {#syntax#}+%{#endsyntax#} and {#syntax#}-%{#endsyntax#} perform wrapping arithmetic 1073 while {#syntax#}+|{#endsyntax#} and {#syntax#}-|{#endsyntax#} perform saturating arithmetic. 1074 </p> 1075 <p> 1076 Zig supports arbitrary bit-width integers, referenced by using 1077 an identifier of <code>i</code> or <code>u</code> followed by digits. For example, the identifier 1078 {#syntax#}i7{#endsyntax#} refers to a signed 7-bit integer. The maximum allowed bit-width of an 1079 integer type is {#syntax#}65535{#endsyntax#}. For signed integer types, Zig uses a 1080 <a href="https://en.wikipedia.org/wiki/Two's_complement">two's complement</a> representation. 1081 </p> 1082 {#see_also|Wrapping Operations#} 1083 {#header_close#} 1084 {#header_close#} 1085 {#header_open|Floats#} 1086 <p>Zig has the following floating point types:</p> 1087 <ul> 1088 <li>{#syntax#}f16{#endsyntax#} - IEEE-754-2008 binary16</li> 1089 <li>{#syntax#}f32{#endsyntax#} - IEEE-754-2008 binary32</li> 1090 <li>{#syntax#}f64{#endsyntax#} - IEEE-754-2008 binary64</li> 1091 <li>{#syntax#}f80{#endsyntax#} - IEEE-754-2008 80-bit extended precision</li> 1092 <li>{#syntax#}f128{#endsyntax#} - IEEE-754-2008 binary128</li> 1093 <li>{#syntax#}c_longdouble{#endsyntax#} - matches <code class="c">long double</code> for the target C ABI</li> 1094 </ul> 1095 {#header_open|Float Literals#} 1096 <p> 1097 Float literals have type {#syntax#}comptime_float{#endsyntax#} which is guaranteed to have 1098 the same precision and operations of the largest other floating point type, which is 1099 {#syntax#}f128{#endsyntax#}. 1100 </p> 1101 <p> 1102 Float literals {#link|coerce|Type Coercion#} to any floating point type, 1103 and to any {#link|integer|Integers#} type when there is no fractional component. 1104 </p> 1105 {#code|float_literals.zig#} 1106 1107 <p> 1108 There is no syntax for NaN, infinity, or negative infinity. For these special values, 1109 one must use the standard library: 1110 </p> 1111 {#code|float_special_values.zig#} 1112 1113 {#header_close#} 1114 {#header_open|Floating Point Operations#} 1115 <p>By default floating point operations use {#syntax#}Strict{#endsyntax#} mode, 1116 but you can switch to {#syntax#}Optimized{#endsyntax#} mode on a per-block basis:</p> 1117 {#code|float_mode_obj.zig#} 1118 1119 <p>For this test we have to separate code into two object files - 1120 otherwise the optimizer figures out all the values at compile-time, 1121 which operates in strict mode.</p> 1122 {#code|float_mode_exe.zig#} 1123 1124 {#see_also|@setFloatMode|Division by Zero#} 1125 {#header_close#} 1126 {#header_close#} 1127 {#header_open|Operators#} 1128 <p> 1129 There is no operator overloading. When you see an operator in Zig, you know that 1130 it is doing something from this table, and nothing else. 1131 </p> 1132 {#header_open|Table of Operators#} 1133 <div class="table-wrapper"> 1134 <table> 1135 <thead> 1136 <tr> 1137 <th scope="col">Name</th> 1138 <th scope="col">Syntax</th> 1139 <th scope="col">Types</th> 1140 <th scope="col">Remarks</th> 1141 <th scope="col">Example</th> 1142 </tr> 1143 </thead> 1144 <tbody> 1145 <tr> 1146 <td>Addition</td> 1147 <td><pre>{#syntax#}a + b 1148 a += b{#endsyntax#}</pre></td> 1149 <td> 1150 <ul> 1151 <li>{#link|Integers#}</li> 1152 <li>{#link|Floats#}</li> 1153 </ul> 1154 </td> 1155 <td> 1156 <ul> 1157 <li>Can cause {#link|overflow|Default Operations#} for integers.</li> 1158 <li>Invokes {#link|Peer Type Resolution#} for the operands.</li> 1159 <li>See also {#link|@addWithOverflow#}.</li> 1160 </ul> 1161 </td> 1162 <td> 1163 <pre>{#syntax#}2 + 5 == 7{#endsyntax#}</pre> 1164 </td> 1165 </tr> 1166 <tr> 1167 <td>Wrapping Addition</td> 1168 <td><pre>{#syntax#}a +% b 1169 a +%= b{#endsyntax#}</pre></td> 1170 <td> 1171 <ul> 1172 <li>{#link|Integers#}</li> 1173 </ul> 1174 </td> 1175 <td> 1176 <ul> 1177 <li>Twos-complement wrapping behavior.</li> 1178 <li>Invokes {#link|Peer Type Resolution#} for the operands.</li> 1179 <li>See also {#link|@addWithOverflow#}.</li> 1180 </ul> 1181 </td> 1182 <td> 1183 <pre>{#syntax#}@as(u32, 0xffffffff) +% 1 == 0{#endsyntax#}</pre> 1184 </td> 1185 </tr> 1186 <tr> 1187 <td>Saturating Addition</td> 1188 <td><pre>{#syntax#}a +| b 1189 a +|= b{#endsyntax#}</pre></td> 1190 <td> 1191 <ul> 1192 <li>{#link|Integers#}</li> 1193 </ul> 1194 </td> 1195 <td> 1196 <ul> 1197 <li>Invokes {#link|Peer Type Resolution#} for the operands.</li> 1198 </ul> 1199 </td> 1200 <td> 1201 <pre>{#syntax#}@as(u8, 255) +| 1 == @as(u8, 255){#endsyntax#}</pre> 1202 </td> 1203 </tr> 1204 <tr> 1205 <td>Subtraction</td> 1206 <td><pre>{#syntax#}a - b 1207 a -= b{#endsyntax#}</pre></td> 1208 <td> 1209 <ul> 1210 <li>{#link|Integers#}</li> 1211 <li>{#link|Floats#}</li> 1212 </ul> 1213 </td> 1214 <td> 1215 <ul> 1216 <li>Can cause {#link|overflow|Default Operations#} for integers.</li> 1217 <li>Invokes {#link|Peer Type Resolution#} for the operands.</li> 1218 <li>See also {#link|@subWithOverflow#}.</li> 1219 </ul> 1220 </td> 1221 <td> 1222 <pre>{#syntax#}2 - 5 == -3{#endsyntax#}</pre> 1223 </td> 1224 </tr> 1225 <tr> 1226 <td>Wrapping Subtraction</td> 1227 <td><pre>{#syntax#}a -% b 1228 a -%= b{#endsyntax#}</pre></td> 1229 <td> 1230 <ul> 1231 <li>{#link|Integers#}</li> 1232 </ul> 1233 </td> 1234 <td> 1235 <ul> 1236 <li>Twos-complement wrapping behavior.</li> 1237 <li>Invokes {#link|Peer Type Resolution#} for the operands.</li> 1238 <li>See also {#link|@subWithOverflow#}.</li> 1239 </ul> 1240 </td> 1241 <td> 1242 <pre>{#syntax#}@as(u8, 0) -% 1 == 255{#endsyntax#}</pre> 1243 </td> 1244 </tr> 1245 <tr> 1246 <td>Saturating Subtraction</td> 1247 <td><pre>{#syntax#}a -| b 1248 a -|= b{#endsyntax#}</pre></td> 1249 <td> 1250 <ul> 1251 <li>{#link|Integers#}</li> 1252 </ul> 1253 </td> 1254 <td> 1255 <ul> 1256 <li>Invokes {#link|Peer Type Resolution#} for the operands.</li> 1257 </ul> 1258 </td> 1259 <td> 1260 <pre>{#syntax#}@as(u32, 0) -| 1 == 0{#endsyntax#}</pre> 1261 </td> 1262 </tr> 1263 <tr> 1264 <td>Negation</td> 1265 <td><pre>{#syntax#}-a{#endsyntax#}</pre></td> 1266 <td> 1267 <ul> 1268 <li>{#link|Integers#}</li> 1269 <li>{#link|Floats#}</li> 1270 </ul> 1271 </td> 1272 <td> 1273 <ul> 1274 <li>Can cause {#link|overflow|Default Operations#} for integers.</li> 1275 </ul> 1276 </td> 1277 <td> 1278 <pre>{#syntax#}-1 == 0 - 1{#endsyntax#}</pre> 1279 </td> 1280 </tr> 1281 <tr> 1282 <td>Wrapping Negation</td> 1283 <td><pre>{#syntax#}-%a{#endsyntax#}</pre></td> 1284 <td> 1285 <ul> 1286 <li>{#link|Integers#}</li> 1287 </ul> 1288 </td> 1289 <td> 1290 <ul> 1291 <li>Twos-complement wrapping behavior.</li> 1292 </ul> 1293 </td> 1294 <td> 1295 <pre>{#syntax#}-%@as(i8, -128) == -128{#endsyntax#}</pre> 1296 </td> 1297 </tr> 1298 <tr> 1299 <td>Multiplication</td> 1300 <td><pre>{#syntax#}a * b 1301 a *= b{#endsyntax#}</pre></td> 1302 <td> 1303 <ul> 1304 <li>{#link|Integers#}</li> 1305 <li>{#link|Floats#}</li> 1306 </ul> 1307 </td> 1308 <td> 1309 <ul> 1310 <li>Can cause {#link|overflow|Default Operations#} for integers.</li> 1311 <li>Invokes {#link|Peer Type Resolution#} for the operands.</li> 1312 <li>See also {#link|@mulWithOverflow#}.</li> 1313 </ul> 1314 </td> 1315 <td> 1316 <pre>{#syntax#}2 * 5 == 10{#endsyntax#}</pre> 1317 </td> 1318 </tr> 1319 <tr> 1320 <td>Wrapping Multiplication</td> 1321 <td><pre>{#syntax#}a *% b 1322 a *%= b{#endsyntax#}</pre></td> 1323 <td> 1324 <ul> 1325 <li>{#link|Integers#}</li> 1326 </ul> 1327 </td> 1328 <td> 1329 <ul> 1330 <li>Twos-complement wrapping behavior.</li> 1331 <li>Invokes {#link|Peer Type Resolution#} for the operands.</li> 1332 <li>See also {#link|@mulWithOverflow#}.</li> 1333 </ul> 1334 </td> 1335 <td> 1336 <pre>{#syntax#}@as(u8, 200) *% 2 == 144{#endsyntax#}</pre> 1337 </td> 1338 </tr> 1339 <tr> 1340 <td>Saturating Multiplication</td> 1341 <td><pre>{#syntax#}a *| b 1342 a *|= b{#endsyntax#}</pre></td> 1343 <td> 1344 <ul> 1345 <li>{#link|Integers#}</li> 1346 </ul> 1347 </td> 1348 <td> 1349 <ul> 1350 <li>Invokes {#link|Peer Type Resolution#} for the operands.</li> 1351 </ul> 1352 </td> 1353 <td> 1354 <pre>{#syntax#}@as(u8, 200) *| 2 == 255{#endsyntax#}</pre> 1355 </td> 1356 </tr> 1357 <tr> 1358 <td>Division</td> 1359 <td><pre>{#syntax#}a / b 1360 a /= b{#endsyntax#}</pre></td> 1361 <td> 1362 <ul> 1363 <li>{#link|Integers#}</li> 1364 <li>{#link|Floats#}</li> 1365 </ul> 1366 </td> 1367 <td> 1368 <ul> 1369 <li>Can cause {#link|overflow|Default Operations#} for integers.</li> 1370 <li>Can cause {#link|Division by Zero#} for integers.</li> 1371 <li>Can cause {#link|Division by Zero#} for floats in {#link|FloatMode.Optimized Mode|Floating Point Operations#}.</li> 1372 <li>Signed integer operands must be comptime-known and positive. In other cases, use 1373 {#link|@divTrunc#}, 1374 {#link|@divFloor#}, or 1375 {#link|@divExact#} instead. 1376 </li> 1377 <li>Invokes {#link|Peer Type Resolution#} for the operands.</li> 1378 </ul> 1379 </td> 1380 <td> 1381 <pre>{#syntax#}10 / 5 == 2{#endsyntax#}</pre> 1382 </td> 1383 </tr> 1384 <tr> 1385 <td>Remainder Division</td> 1386 <td><pre>{#syntax#}a % b 1387 a %= b{#endsyntax#}</pre></td> 1388 <td> 1389 <ul> 1390 <li>{#link|Integers#}</li> 1391 <li>{#link|Floats#}</li> 1392 </ul> 1393 </td> 1394 <td> 1395 <ul> 1396 <li>Can cause {#link|Division by Zero#} for integers.</li> 1397 <li>Can cause {#link|Division by Zero#} for floats in {#link|FloatMode.Optimized Mode|Floating Point Operations#}.</li> 1398 <li>Signed or floating-point operands must be comptime-known and positive. In other cases, use 1399 {#link|@rem#} or 1400 {#link|@mod#} instead. 1401 </li> 1402 <li>Invokes {#link|Peer Type Resolution#} for the operands.</li> 1403 </ul> 1404 </td> 1405 <td> 1406 <pre>{#syntax#}10 % 3 == 1{#endsyntax#}</pre> 1407 </td> 1408 </tr> 1409 <tr> 1410 <td>Bit Shift Left</td> 1411 <td><pre>{#syntax#}a << b 1412 a <<= b{#endsyntax#}</pre></td> 1413 <td> 1414 <ul> 1415 <li>{#link|Integers#}</li> 1416 </ul> 1417 </td> 1418 <td> 1419 <ul> 1420 <li>Moves all bits to the left, inserting new zeroes at the 1421 least-significant bit.</li> 1422 <li>{#syntax#}b{#endsyntax#} must be 1423 {#link|comptime-known|comptime#} or have a type with log2 number 1424 of bits as {#syntax#}a{#endsyntax#}.</li> 1425 <li>See also {#link|@shlExact#}.</li> 1426 <li>See also {#link|@shlWithOverflow#}.</li> 1427 </ul> 1428 </td> 1429 <td> 1430 <pre>{#syntax#}0b1 << 8 == 0b100000000{#endsyntax#}</pre> 1431 </td> 1432 </tr> 1433 <tr> 1434 <td>Saturating Bit Shift Left</td> 1435 <td><pre>{#syntax#}a <<| b 1436 a <<|= b{#endsyntax#}</pre></td> 1437 <td> 1438 <ul> 1439 <li>{#link|Integers#}</li> 1440 </ul> 1441 </td> 1442 <td> 1443 <ul> 1444 <li>See also {#link|@shlExact#}.</li> 1445 <li>See also {#link|@shlWithOverflow#}.</li> 1446 </ul> 1447 </td> 1448 <td> 1449 <pre>{#syntax#}@as(u8, 1) <<| 8 == 255{#endsyntax#}</pre> 1450 </td> 1451 </tr> 1452 <tr> 1453 <td>Bit Shift Right</td> 1454 <td><pre>{#syntax#}a >> b 1455 a >>= b{#endsyntax#}</pre></td> 1456 <td> 1457 <ul> 1458 <li>{#link|Integers#}</li> 1459 </ul> 1460 </td> 1461 <td> 1462 <ul> 1463 <li>Moves all bits to the right, inserting zeroes at the most-significant bit.</li> 1464 <li>{#syntax#}b{#endsyntax#} must be 1465 {#link|comptime-known|comptime#} or have a type with log2 number 1466 of bits as {#syntax#}a{#endsyntax#}.</li> 1467 <li>See also {#link|@shrExact#}.</li> 1468 </ul> 1469 </td> 1470 <td> 1471 <pre>{#syntax#}0b1010 >> 1 == 0b101{#endsyntax#}</pre> 1472 </td> 1473 </tr> 1474 <tr> 1475 <td>Bitwise And</td> 1476 <td><pre>{#syntax#}a & b 1477 a &= b{#endsyntax#}</pre></td> 1478 <td> 1479 <ul> 1480 <li>{#link|Integers#}</li> 1481 </ul> 1482 </td> 1483 <td> 1484 <ul> 1485 <li>Invokes {#link|Peer Type Resolution#} for the operands.</li> 1486 </ul> 1487 </td> 1488 <td> 1489 <pre>{#syntax#}0b011 & 0b101 == 0b001{#endsyntax#}</pre> 1490 </td> 1491 </tr> 1492 <tr> 1493 <td>Bitwise Or</td> 1494 <td><pre>{#syntax#}a | b 1495 a |= b{#endsyntax#}</pre></td> 1496 <td> 1497 <ul> 1498 <li>{#link|Integers#}</li> 1499 </ul> 1500 </td> 1501 <td> 1502 <ul> 1503 <li>Invokes {#link|Peer Type Resolution#} for the operands.</li> 1504 </ul> 1505 </td> 1506 <td> 1507 <pre>{#syntax#}0b010 | 0b100 == 0b110{#endsyntax#}</pre> 1508 </td> 1509 </tr> 1510 <tr> 1511 <td>Bitwise Xor</td> 1512 <td><pre>{#syntax#}a ^ b 1513 a ^= b{#endsyntax#}</pre></td> 1514 <td> 1515 <ul> 1516 <li>{#link|Integers#}</li> 1517 </ul> 1518 </td> 1519 <td> 1520 <ul> 1521 <li>Invokes {#link|Peer Type Resolution#} for the operands.</li> 1522 </ul> 1523 </td> 1524 <td> 1525 <pre>{#syntax#}0b011 ^ 0b101 == 0b110{#endsyntax#}</pre> 1526 </td> 1527 </tr> 1528 <tr> 1529 <td>Bitwise Not</td> 1530 <td><pre>{#syntax#}~a{#endsyntax#}</pre></td> 1531 <td> 1532 <ul> 1533 <li>{#link|Integers#}</li> 1534 </ul> 1535 </td> 1536 <td></td> 1537 <td> 1538 <pre>{#syntax#}~@as(u8, 0b10101111) == 0b01010000{#endsyntax#}</pre> 1539 </td> 1540 </tr> 1541 <tr> 1542 <td>Defaulting Optional Unwrap</td> 1543 <td><pre>{#syntax#}a orelse b{#endsyntax#}</pre></td> 1544 <td> 1545 <ul> 1546 <li>{#link|Optionals#}</li> 1547 </ul> 1548 </td> 1549 <td>If {#syntax#}a{#endsyntax#} is {#syntax#}null{#endsyntax#}, 1550 returns {#syntax#}b{#endsyntax#} ("default value"), 1551 otherwise returns the unwrapped value of {#syntax#}a{#endsyntax#}. 1552 Note that {#syntax#}b{#endsyntax#} may be a value of type {#link|noreturn#}. 1553 </td> 1554 <td> 1555 <pre>{#syntax#}const value: ?u32 = null; 1556 const unwrapped = value orelse 1234; 1557 unwrapped == 1234{#endsyntax#}</pre> 1558 </td> 1559 </tr> 1560 <tr> 1561 <td>Optional Unwrap</td> 1562 <td><pre>{#syntax#}a.?{#endsyntax#}</pre></td> 1563 <td> 1564 <ul> 1565 <li>{#link|Optionals#}</li> 1566 </ul> 1567 </td> 1568 <td> 1569 Equivalent to: 1570 <pre>{#syntax#}a orelse unreachable{#endsyntax#}</pre> 1571 </td> 1572 <td> 1573 <pre>{#syntax#}const value: ?u32 = 5678; 1574 value.? == 5678{#endsyntax#}</pre> 1575 </td> 1576 </tr> 1577 <tr> 1578 <td>Defaulting Error Unwrap</td> 1579 <td><pre>{#syntax#}a catch b 1580 a catch |err| b{#endsyntax#}</pre></td> 1581 <td> 1582 <ul> 1583 <li>{#link|Error Unions|Errors#}</li> 1584 </ul> 1585 </td> 1586 <td>If {#syntax#}a{#endsyntax#} is an {#syntax#}error{#endsyntax#}, 1587 returns {#syntax#}b{#endsyntax#} ("default value"), 1588 otherwise returns the unwrapped value of {#syntax#}a{#endsyntax#}. 1589 Note that {#syntax#}b{#endsyntax#} may be a value of type {#link|noreturn#}. 1590 {#syntax#}err{#endsyntax#} is the {#syntax#}error{#endsyntax#} and is in scope of the expression {#syntax#}b{#endsyntax#}. 1591 </td> 1592 <td> 1593 <pre>{#syntax#}const value: anyerror!u32 = error.Broken; 1594 const unwrapped = value catch 1234; 1595 unwrapped == 1234{#endsyntax#}</pre> 1596 </td> 1597 </tr> 1598 <tr> 1599 <td>Logical And</td> 1600 <td><pre>{#syntax#}a and b{#endsyntax#}</pre></td> 1601 <td> 1602 <ul> 1603 <li>{#link|bool|Primitive Types#}</li> 1604 </ul> 1605 </td> 1606 <td> 1607 If {#syntax#}a{#endsyntax#} is {#syntax#}false{#endsyntax#}, returns {#syntax#}false{#endsyntax#} 1608 without evaluating {#syntax#}b{#endsyntax#}. Otherwise, returns {#syntax#}b{#endsyntax#}. 1609 </td> 1610 <td> 1611 <pre>{#syntax#}(false and true) == false{#endsyntax#}</pre> 1612 </td> 1613 </tr> 1614 <tr> 1615 <td>Logical Or</td> 1616 <td><pre>{#syntax#}a or b{#endsyntax#}</pre></td> 1617 <td> 1618 <ul> 1619 <li>{#link|bool|Primitive Types#}</li> 1620 </ul> 1621 </td> 1622 <td> 1623 If {#syntax#}a{#endsyntax#} is {#syntax#}true{#endsyntax#}, 1624 returns {#syntax#}true{#endsyntax#} without evaluating 1625 {#syntax#}b{#endsyntax#}. Otherwise, returns 1626 {#syntax#}b{#endsyntax#}. 1627 </td> 1628 <td> 1629 <pre>{#syntax#}(false or true) == true{#endsyntax#}</pre> 1630 </td> 1631 </tr> 1632 <tr> 1633 <td>Boolean Not</td> 1634 <td><pre>{#syntax#}!a{#endsyntax#}</pre></td> 1635 <td> 1636 <ul> 1637 <li>{#link|bool|Primitive Types#}</li> 1638 </ul> 1639 </td> 1640 <td></td> 1641 <td> 1642 <pre>{#syntax#}!false == true{#endsyntax#}</pre> 1643 </td> 1644 </tr> 1645 <tr> 1646 <td>Equality</td> 1647 <td><pre>{#syntax#}a == b{#endsyntax#}</pre></td> 1648 <td> 1649 <ul> 1650 <li>{#link|Integers#}</li> 1651 <li>{#link|Floats#}</li> 1652 <li>{#link|bool|Primitive Types#}</li> 1653 <li>{#link|type|Primitive Types#}</li> 1654 <li>{#link|packed struct#}</li> 1655 </ul> 1656 </td> 1657 <td> 1658 Returns {#syntax#}true{#endsyntax#} if a and b are equal, otherwise returns {#syntax#}false{#endsyntax#}. 1659 Invokes {#link|Peer Type Resolution#} for the operands. 1660 </td> 1661 <td> 1662 <pre>{#syntax#}(1 == 1) == true{#endsyntax#}</pre> 1663 </td> 1664 </tr> 1665 <tr> 1666 <td>Null Check</td> 1667 <td><pre>{#syntax#}a == null{#endsyntax#}</pre></td> 1668 <td> 1669 <ul> 1670 <li>{#link|Optionals#}</li> 1671 </ul> 1672 </td> 1673 <td> 1674 Returns {#syntax#}true{#endsyntax#} if a is {#syntax#}null{#endsyntax#}, otherwise returns {#syntax#}false{#endsyntax#}. 1675 </td> 1676 <td> 1677 <pre>{#syntax#}const value: ?u32 = null; 1678 (value == null) == true{#endsyntax#}</pre> 1679 </td> 1680 </tr> 1681 <tr> 1682 <td>Inequality</td> 1683 <td><pre>{#syntax#}a != b{#endsyntax#}</pre></td> 1684 <td> 1685 <ul> 1686 <li>{#link|Integers#}</li> 1687 <li>{#link|Floats#}</li> 1688 <li>{#link|bool|Primitive Types#}</li> 1689 <li>{#link|type|Primitive Types#}</li> 1690 </ul> 1691 </td> 1692 <td> 1693 Returns {#syntax#}false{#endsyntax#} if a and b are equal, otherwise returns {#syntax#}true{#endsyntax#}. 1694 Invokes {#link|Peer Type Resolution#} for the operands. 1695 </td> 1696 <td> 1697 <pre>{#syntax#}(1 != 1) == false{#endsyntax#}</pre> 1698 </td> 1699 </tr> 1700 <tr> 1701 <td>Non-Null Check</td> 1702 <td><pre>{#syntax#}a != null{#endsyntax#}</pre></td> 1703 <td> 1704 <ul> 1705 <li>{#link|Optionals#}</li> 1706 </ul> 1707 </td> 1708 <td> 1709 Returns {#syntax#}false{#endsyntax#} if a is {#syntax#}null{#endsyntax#}, otherwise returns {#syntax#}true{#endsyntax#}. 1710 </td> 1711 <td> 1712 <pre>{#syntax#}const value: ?u32 = null; 1713 (value != null) == false{#endsyntax#}</pre> 1714 </td> 1715 </tr> 1716 <tr> 1717 <td>Greater Than</td> 1718 <td><pre>{#syntax#}a > b{#endsyntax#}</pre></td> 1719 <td> 1720 <ul> 1721 <li>{#link|Integers#}</li> 1722 <li>{#link|Floats#}</li> 1723 </ul> 1724 </td> 1725 <td> 1726 Returns {#syntax#}true{#endsyntax#} if a is greater than b, otherwise returns {#syntax#}false{#endsyntax#}. 1727 Invokes {#link|Peer Type Resolution#} for the operands. 1728 </td> 1729 <td> 1730 <pre>{#syntax#}(2 > 1) == true{#endsyntax#}</pre> 1731 </td> 1732 </tr> 1733 <tr> 1734 <td>Greater or Equal</td> 1735 <td><pre>{#syntax#}a >= b{#endsyntax#}</pre></td> 1736 <td> 1737 <ul> 1738 <li>{#link|Integers#}</li> 1739 <li>{#link|Floats#}</li> 1740 </ul> 1741 </td> 1742 <td> 1743 Returns {#syntax#}true{#endsyntax#} if a is greater than or equal to b, otherwise returns {#syntax#}false{#endsyntax#}. 1744 Invokes {#link|Peer Type Resolution#} for the operands. 1745 </td> 1746 <td> 1747 <pre>{#syntax#}(2 >= 1) == true{#endsyntax#}</pre> 1748 </td> 1749 </tr> 1750 <tr> 1751 <td>Less Than</td> 1752 <td><pre>{#syntax#}a < b{#endsyntax#}</pre></td> 1753 <td> 1754 <ul> 1755 <li>{#link|Integers#}</li> 1756 <li>{#link|Floats#}</li> 1757 </ul> 1758 </td> 1759 <td> 1760 Returns {#syntax#}true{#endsyntax#} if a is less than b, otherwise returns {#syntax#}false{#endsyntax#}. 1761 Invokes {#link|Peer Type Resolution#} for the operands. 1762 </td> 1763 <td> 1764 <pre>{#syntax#}(1 < 2) == true{#endsyntax#}</pre> 1765 </td> 1766 </tr> 1767 <tr> 1768 <td>Lesser or Equal</td> 1769 <td><pre>{#syntax#}a <= b{#endsyntax#}</pre></td> 1770 <td> 1771 <ul> 1772 <li>{#link|Integers#}</li> 1773 <li>{#link|Floats#}</li> 1774 </ul> 1775 </td> 1776 <td> 1777 Returns {#syntax#}true{#endsyntax#} if a is less than or equal to b, otherwise returns {#syntax#}false{#endsyntax#}. 1778 Invokes {#link|Peer Type Resolution#} for the operands. 1779 </td> 1780 <td> 1781 <pre>{#syntax#}(1 <= 2) == true{#endsyntax#}</pre> 1782 </td> 1783 </tr> 1784 <tr> 1785 <td>Array Concatenation</td> 1786 <td><pre>{#syntax#}a ++ b{#endsyntax#}</pre></td> 1787 <td> 1788 <ul> 1789 <li>{#link|Arrays#}</li> 1790 </ul> 1791 </td> 1792 <td> 1793 <ul> 1794 <li>Only available when the lengths of both {#syntax#}a{#endsyntax#} and {#syntax#}b{#endsyntax#} are {#link|compile-time known|comptime#}.</li> 1795 </ul> 1796 </td> 1797 <td> 1798 <pre>{#syntax#}const mem = @import("std").mem; 1799 const array1 = [_]u32{1,2}; 1800 const array2 = [_]u32{3,4}; 1801 const together = array1 ++ array2; 1802 mem.eql(u32, &together, &[_]u32{1,2,3,4}){#endsyntax#}</pre> 1803 </td> 1804 </tr> 1805 <tr> 1806 <td>Array Multiplication</td> 1807 <td><pre>{#syntax#}a ** b{#endsyntax#}</pre></td> 1808 <td> 1809 <ul> 1810 <li>{#link|Arrays#}</li> 1811 </ul> 1812 </td> 1813 <td> 1814 <ul> 1815 <li>Only available when the length of {#syntax#}a{#endsyntax#} and {#syntax#}b{#endsyntax#} are {#link|compile-time known|comptime#}.</li> 1816 </ul> 1817 </td> 1818 <td> 1819 <pre>{#syntax#}const mem = @import("std").mem; 1820 const pattern = "ab" ** 3; 1821 mem.eql(u8, pattern, "ababab"){#endsyntax#}</pre> 1822 </td> 1823 </tr> 1824 <tr> 1825 <td>Pointer Dereference</td> 1826 <td><pre>{#syntax#}a.*{#endsyntax#}</pre></td> 1827 <td> 1828 <ul> 1829 <li>{#link|Pointers#}</li> 1830 </ul> 1831 </td> 1832 <td> 1833 Pointer dereference. 1834 </td> 1835 <td> 1836 <pre>{#syntax#}const x: u32 = 1234; 1837 const ptr = &x; 1838 ptr.* == 1234{#endsyntax#}</pre> 1839 </td> 1840 </tr> 1841 <tr> 1842 <td>Address Of</td> 1843 <td><pre>{#syntax#}&a{#endsyntax#}</pre></td> 1844 <td> 1845 All types 1846 </td> 1847 <td> 1848 </td> 1849 <td> 1850 <pre>{#syntax#}const x: u32 = 1234; 1851 const ptr = &x; 1852 ptr.* == 1234{#endsyntax#}</pre> 1853 </td> 1854 </tr> 1855 <tr> 1856 <td>Error Set Merge</td> 1857 <td><pre>{#syntax#}a || b{#endsyntax#}</pre></td> 1858 <td> 1859 <ul> 1860 <li>{#link|Error Set Type#}</li> 1861 </ul> 1862 </td> 1863 <td> 1864 {#link|Merging Error Sets#} 1865 </td> 1866 <td> 1867 <pre>{#syntax#}const A = error{One}; 1868 const B = error{Two}; 1869 (A || B) == error{One, Two}{#endsyntax#}</pre> 1870 </td> 1871 </tr> 1872 </tbody> 1873 </table> 1874 </div> 1875 {#header_close#} 1876 {#header_open|Precedence#} 1877 <pre>{#syntax#}x() x[] x.y x.* x.? 1878 a!b 1879 x{} 1880 !x -x -%x ~x &x ?x 1881 * / % ** *% *| || 1882 + - ++ +% -% +| -| 1883 << >> <<| 1884 & ^ | orelse catch 1885 == != < > <= >= 1886 and 1887 or 1888 = *= *%= *|= /= %= += +%= +|= -= -%= -|= <<= <<|= >>= &= ^= |={#endsyntax#}</pre> 1889 {#header_close#} 1890 {#header_close#} 1891 {#header_open|Arrays#} 1892 {#code|test_arrays.zig#} 1893 1894 {#see_also|for|Slices#} 1895 1896 {#header_open|Multidimensional Arrays#} 1897 <p> 1898 Multidimensional arrays can be created by nesting arrays: 1899 </p> 1900 {#code|test_multidimensional_arrays.zig#} 1901 1902 {#header_close#} 1903 1904 {#header_open|Sentinel-Terminated Arrays#} 1905 <p> 1906 The syntax {#syntax#}[N:x]T{#endsyntax#} describes an array which has a sentinel element of value {#syntax#}x{#endsyntax#} at the 1907 index corresponding to the length {#syntax#}N{#endsyntax#}. 1908 </p> 1909 {#code|test_null_terminated_array.zig#} 1910 1911 {#see_also|Sentinel-Terminated Pointers|Sentinel-Terminated Slices#} 1912 {#header_close#} 1913 1914 {#header_open|Destructuring Arrays#} 1915 <p> 1916 Arrays can be destructured: 1917 </p> 1918 {#code|destructuring_arrays.zig#} 1919 1920 {#see_also|Destructuring|Destructuring Tuples|Destructuring Vectors#} 1921 {#header_close#} 1922 {#header_close#} 1923 1924 {#header_open|Vectors#} 1925 <p> 1926 A vector is a group of booleans, {#link|Integers#}, {#link|Floats#}, or 1927 {#link|Pointers#} which are operated on in parallel, using SIMD instructions if possible. 1928 Vector types are created with the builtin function {#link|@Vector#}. 1929 </p> 1930 <p> 1931 Vectors generally support the same builtin operators as their underlying base types. 1932 The only exception to this is the keywords `and` and `or` on vectors of bools, since 1933 these operators affect control flow, which is not allowed for vectors. 1934 All other operations are performed element-wise, and return a vector of the same length 1935 as the input vectors. This includes: 1936 </p> 1937 <ul> 1938 <li>Arithmetic ({#syntax#}+{#endsyntax#}, {#syntax#}-{#endsyntax#}, {#syntax#}/{#endsyntax#}, {#syntax#}*{#endsyntax#}, 1939 {#syntax#}@divFloor{#endsyntax#}, {#syntax#}@sqrt{#endsyntax#}, {#syntax#}@ceil{#endsyntax#}, 1940 {#syntax#}@log{#endsyntax#}, etc.)</li> 1941 <li>Bitwise operators ({#syntax#}>>{#endsyntax#}, {#syntax#}<<{#endsyntax#}, {#syntax#}&{#endsyntax#}, 1942 {#syntax#}|{#endsyntax#}, {#syntax#}~{#endsyntax#}, etc.)</li> 1943 <li>Comparison operators ({#syntax#}<{#endsyntax#}, {#syntax#}>{#endsyntax#}, {#syntax#}=={#endsyntax#}, etc.)</li> 1944 <li>Boolean not ({#syntax#}!{#endsyntax#})</li> 1945 </ul> 1946 <p> 1947 It is prohibited to use a math operator on a mixture of scalars (individual numbers) 1948 and vectors. Zig provides the {#link|@splat#} builtin to easily convert from scalars 1949 to vectors, and it supports {#link|@reduce#} and array indexing syntax to convert 1950 from vectors to scalars. Vectors also support assignment to and from fixed-length 1951 arrays with comptime-known length. 1952 </p> 1953 <p> 1954 For rearranging elements within and between vectors, Zig provides the {#link|@shuffle#} and {#link|@select#} functions. 1955 </p> 1956 <p> 1957 Operations on vectors shorter than the target machine's native SIMD size will typically compile to single SIMD 1958 instructions, while vectors longer than the target machine's native SIMD size will compile to multiple SIMD 1959 instructions. If a given operation doesn't have SIMD support on the target architecture, the compiler will default 1960 to operating on each vector element one at a time. Zig supports any comptime-known vector length up to 2^32-1, 1961 although small powers of two (2-64) are most typical. Note that excessively long vector lengths (e.g. 2^20) may 1962 result in compiler crashes on current versions of Zig. 1963 </p> 1964 {#code|test_vector.zig#} 1965 1966 <p> 1967 TODO talk about C ABI interop<br> 1968 TODO consider suggesting std.MultiArrayList 1969 </p> 1970 {#see_also|@splat|@shuffle|@select|@reduce#} 1971 1972 {#header_open|Destructuring Vectors#} 1973 <p> 1974 Vectors can be destructured: 1975 </p> 1976 {#code|destructuring_vectors.zig#} 1977 {#see_also|Destructuring|Destructuring Tuples|Destructuring Arrays#} 1978 {#header_close#} 1979 1980 {#header_close#} 1981 1982 {#header_open|Pointers#} 1983 <p> 1984 Zig has two kinds of pointers: single-item and many-item. 1985 </p> 1986 <ul> 1987 <li>{#syntax#}*T{#endsyntax#} - single-item pointer to exactly one item. 1988 <ul> 1989 <li>Supports deref syntax: {#syntax#}ptr.*{#endsyntax#}</li> 1990 <li>Supports slice syntax: {#syntax#}ptr[0..1]{#endsyntax#}</li> 1991 <li>Supports pointer subtraction: {#syntax#}ptr - ptr{#endsyntax#}</li> 1992 </ul> 1993 </li> 1994 <li>{#syntax#}[*]T{#endsyntax#} - many-item pointer to unknown number of items. 1995 <ul> 1996 <li>Supports index syntax: {#syntax#}ptr[i]{#endsyntax#}</li> 1997 <li>Supports slice syntax: {#syntax#}ptr[start..end]{#endsyntax#} and {#syntax#}ptr[start..]{#endsyntax#}</li> 1998 <li>Supports pointer-integer arithmetic: {#syntax#}ptr + int{#endsyntax#}, {#syntax#}ptr - int{#endsyntax#}</li> 1999 <li>Supports pointer subtraction: {#syntax#}ptr - ptr{#endsyntax#}</li> 2000 </ul> 2001 {#syntax#}T{#endsyntax#} must have a known size, which means that it cannot be 2002 {#syntax#}anyopaque{#endsyntax#} or any other {#link|opaque type|opaque#}. 2003 </li> 2004 </ul> 2005 <p>These types are closely related to {#link|Arrays#} and {#link|Slices#}:</p> 2006 <ul> 2007 <li>{#syntax#}*[N]T{#endsyntax#} - pointer to N items, same as single-item pointer to an array. 2008 <ul> 2009 <li>Supports index syntax: {#syntax#}array_ptr[i]{#endsyntax#}</li> 2010 <li>Supports slice syntax: {#syntax#}array_ptr[start..end]{#endsyntax#}</li> 2011 <li>Supports len property: {#syntax#}array_ptr.len{#endsyntax#}</li> 2012 <li>Supports pointer subtraction: {#syntax#}array_ptr - array_ptr{#endsyntax#}</li> 2013 </ul> 2014 </li> 2015 </ul> 2016 <ul> 2017 <li>{#syntax#}[]T{#endsyntax#} - is a slice (a fat pointer, which contains a pointer of type {#syntax#}[*]T{#endsyntax#} and a length). 2018 <ul> 2019 <li>Supports index syntax: {#syntax#}slice[i]{#endsyntax#}</li> 2020 <li>Supports slice syntax: {#syntax#}slice[start..end]{#endsyntax#}</li> 2021 <li>Supports len property: {#syntax#}slice.len{#endsyntax#}</li> 2022 </ul> 2023 </li> 2024 </ul> 2025 <p>Use {#syntax#}&x{#endsyntax#} to obtain a single-item pointer:</p> 2026 {#code|test_single_item_pointer.zig#} 2027 2028 <p> 2029 Zig supports pointer arithmetic. It's better to assign the pointer to {#syntax#}[*]T{#endsyntax#} and increment that variable. For example, directly incrementing the pointer from a slice will corrupt it. 2030 </p> 2031 {#code|test_pointer_arithmetic.zig#} 2032 2033 <p> 2034 In Zig, we generally prefer {#link|Slices#} rather than {#link|Sentinel-Terminated Pointers#}. 2035 You can turn an array or pointer into a slice using slice syntax. 2036 </p> 2037 <p> 2038 Slices have bounds checking and are therefore protected 2039 against this kind of Illegal Behavior. This is one reason 2040 we prefer slices to pointers. 2041 </p> 2042 {#code|test_slice_bounds.zig#} 2043 2044 <p>Pointers work at compile-time too, as long as the code does not depend on 2045 an undefined memory layout:</p> 2046 {#code|test_comptime_pointers.zig#} 2047 2048 <p>To convert an integer address into a pointer, use {#syntax#}@ptrFromInt{#endsyntax#}. 2049 To convert a pointer to an integer, use {#syntax#}@intFromPtr{#endsyntax#}:</p> 2050 {#code|test_integer_pointer_conversion.zig#} 2051 2052 <p>Zig is able to preserve memory addresses in comptime code, as long as 2053 the pointer is never dereferenced:</p> 2054 {#code|test_comptime_pointer_conversion.zig#} 2055 2056 <p> 2057 {#link|@ptrCast#} converts a pointer's element type to another. This 2058 creates a new pointer that can cause undetectable Illegal Behavior 2059 depending on the loads and stores that pass through it. Generally, other 2060 kinds of type conversions are preferable to 2061 {#syntax#}@ptrCast{#endsyntax#} if possible. 2062 </p> 2063 {#code|test_pointer_casting.zig#} 2064 2065 {#see_also|Optional Pointers|@ptrFromInt|@intFromPtr|C Pointers#} 2066 {#header_open|volatile#} 2067 <p>Loads and stores are assumed to not have side effects. If a given load or store 2068 should have side effects, such as Memory Mapped Input/Output (MMIO), use {#syntax#}volatile{#endsyntax#}. 2069 In the following code, loads and stores with {#syntax#}mmio_ptr{#endsyntax#} are guaranteed to all happen 2070 and in the same order as in source code:</p> 2071 {#code|test_volatile.zig#} 2072 2073 <p> 2074 Note that {#syntax#}volatile{#endsyntax#} is unrelated to concurrency and {#link|Atomics#}. 2075 If you see code that is using {#syntax#}volatile{#endsyntax#} for something other than Memory Mapped 2076 Input/Output, it is probably a bug. 2077 </p> 2078 {#header_close#} 2079 2080 {#header_open|Alignment#} 2081 <p> 2082 Each type has an <strong>alignment</strong> - a number of bytes such that, 2083 when a value of the type is loaded from or stored to memory, 2084 the memory address must be evenly divisible by this number. You can use 2085 {#link|@alignOf#} to find out this value for any type. 2086 </p> 2087 <p> 2088 Alignment depends on the CPU architecture, but is always a power of two, and 2089 less than {#syntax#}1 << 29{#endsyntax#}. 2090 </p> 2091 <p> 2092 In Zig, a pointer type has an alignment value. If the value is equal to the 2093 alignment of the underlying type, it can be omitted from the type: 2094 </p> 2095 {#code|test_variable_alignment.zig#} 2096 2097 <p>In the same way that a {#syntax#}*i32{#endsyntax#} can be {#link|coerced|Type Coercion#} to a 2098 {#syntax#}*const i32{#endsyntax#}, a pointer with a larger alignment can be implicitly 2099 cast to a pointer with a smaller alignment, but not vice versa. 2100 </p> 2101 <p> 2102 You can specify alignment on variables and functions. If you do this, then 2103 pointers to them get the specified alignment: 2104 </p> 2105 {#code|test_variable_func_alignment.zig#} 2106 2107 <p> 2108 If you have a pointer or a slice that has a small alignment, but you know that it actually 2109 has a bigger alignment, use {#link|@alignCast#} to change the 2110 pointer into a more aligned pointer. This is a no-op at runtime, but inserts a 2111 {#link|safety check|Incorrect Pointer Alignment#}: 2112 </p> 2113 {#code|test_incorrect_pointer_alignment.zig#} 2114 2115 {#header_close#} 2116 2117 {#header_open|allowzero#} 2118 <p> 2119 This pointer attribute allows a pointer to have address zero. This is only ever needed on the 2120 freestanding OS target, where the address zero is mappable. If you want to represent null pointers, use 2121 {#link|Optional Pointers#} instead. {#link|Optional Pointers#} with {#syntax#}allowzero{#endsyntax#} 2122 are not the same size as pointers. In this code example, if the pointer 2123 did not have the {#syntax#}allowzero{#endsyntax#} attribute, this would be a 2124 {#link|Pointer Cast Invalid Null#} panic: 2125 </p> 2126 {#code|test_allowzero.zig#} 2127 2128 {#header_close#} 2129 2130 {#header_open|Sentinel-Terminated Pointers#} 2131 <p> 2132 The syntax {#syntax#}[*:x]T{#endsyntax#} describes a pointer that 2133 has a length determined by a sentinel value. This provides protection 2134 against buffer overflow and overreads. 2135 </p> 2136 {#code|sentinel-terminated_pointer.zig#} 2137 2138 {#see_also|Sentinel-Terminated Slices|Sentinel-Terminated Arrays#} 2139 {#header_close#} 2140 {#header_close#} 2141 2142 {#header_open|Slices#} 2143 <p> 2144 A slice is a pointer and a length. The difference between an array and 2145 a slice is that the array's length is part of the type and known at 2146 compile-time, whereas the slice's length is known at runtime. 2147 Both can be accessed with the {#syntax#}len{#endsyntax#} field. 2148 </p> 2149 {#code|test_basic_slices.zig#} 2150 2151 <p>This is one reason we prefer slices to pointers.</p> 2152 {#code|test_slices.zig#} 2153 2154 {#see_also|Pointers|for|Arrays#} 2155 2156 {#header_open|Sentinel-Terminated Slices#} 2157 <p> 2158 The syntax {#syntax#}[:x]T{#endsyntax#} is a slice which has a runtime-known length 2159 and also guarantees a sentinel value at the element indexed by the length. The type does not 2160 guarantee that there are no sentinel elements before that. Sentinel-terminated slices allow element 2161 access to the {#syntax#}len{#endsyntax#} index. 2162 </p> 2163 {#code|test_null_terminated_slice.zig#} 2164 2165 <p> 2166 Sentinel-terminated slices can also be created using a variation of the slice syntax 2167 {#syntax#}data[start..end :x]{#endsyntax#}, where {#syntax#}data{#endsyntax#} is a many-item pointer, 2168 array or slice and {#syntax#}x{#endsyntax#} is the sentinel value. 2169 </p> 2170 {#code|test_null_terminated_slicing.zig#} 2171 2172 <p> 2173 Sentinel-terminated slicing asserts that the element in the sentinel position of the backing data is 2174 actually the sentinel value. If this is not the case, safety-checked {#link|Illegal Behavior#} results. 2175 </p> 2176 {#code|test_sentinel_mismatch.zig#} 2177 2178 {#see_also|Sentinel-Terminated Pointers|Sentinel-Terminated Arrays#} 2179 {#header_close#} 2180 {#header_close#} 2181 2182 {#header_open|struct#} 2183 {#code|test_structs.zig#} 2184 2185 2186 {#header_open|Default Field Values#} 2187 <p> 2188 Each struct field may have an expression indicating the default field 2189 value. Such expressions are executed at {#link|comptime#}, and allow the 2190 field to be omitted in a struct literal expression: 2191 </p> 2192 {#code|struct_default_field_values.zig#} 2193 2194 {#header_open|Faulty Default Field Values#} 2195 <p> 2196 Default field values are only appropriate when the data invariants of a struct 2197 cannot be violated by omitting that field from an initialization. 2198 </p> 2199 <p> 2200 For example, here is an inappropriate use of default struct field initialization: 2201 </p> 2202 {#code|bad_default_value.zig#} 2203 2204 <p> 2205 Above you can see the danger of ignoring this principle. The default 2206 field values caused the data invariant to be violated, causing illegal 2207 behavior. 2208 </p> 2209 <p> 2210 To fix this, remove the default values from all the struct fields, and provide 2211 a named default value: 2212 </p> 2213 {#code|struct_default_value.zig#} 2214 2215 <p>If a struct value requires a runtime-known value in order to be initialized 2216 without violating data invariants, then use an initialization method that accepts 2217 those runtime values, and populates the remaining fields.</p> 2218 {#header_close#} 2219 {#header_close#} 2220 2221 {#header_open|extern struct#} 2222 <p>An {#syntax#}extern struct{#endsyntax#} has in-memory layout matching 2223 the C ABI for the target.</p> 2224 <p>If well-defined in-memory layout is not required, {#link|struct#} is a better choice 2225 because it places fewer restrictions on the compiler.</p> 2226 <p>See {#link|packed struct#} for a struct that has the ABI of its backing integer, 2227 which can be useful for modeling flags.</p> 2228 {#see_also|extern union|extern enum#} 2229 {#header_close#} 2230 2231 {#header_open|packed struct#} 2232 <p> 2233 {#syntax#}packed{#endsyntax#} structs, like {#syntax#}enum{#endsyntax#}, are based on the concept 2234 of interpreting integers differently. All packed structs have a <strong>backing integer</strong>, 2235 which is implicitly determined by the total bit count of fields, or explicitly specified. 2236 Packed structs have well-defined memory layout - exactly the same ABI as their backing integer. 2237 </p> 2238 <p> 2239 Each field of a packed struct is interpreted as a logical sequence of bits, arranged from 2240 least to most significant. Allowed field types: 2241 </p> 2242 <ul> 2243 <li>An {#link|integer|Integers#} field uses exactly as many bits as its 2244 bit width. For example, a {#syntax#}u5{#endsyntax#} will use 5 bits of 2245 the backing integer.</li> 2246 <li>A {#link|bool|Primitive Types#} field uses exactly 1 bit.</li> 2247 <li>An {#link|enum#} field uses exactly the bit width of its integer tag type.</li> 2248 <li>A {#link|packed union#} field uses exactly the bit width of the union field with 2249 the largest bit width.</li> 2250 <li>A {#syntax#}packed struct{#endsyntax#} field uses the bits of its backing integer.</li> 2251 </ul> 2252 <p> 2253 This means that a {#syntax#}packed struct{#endsyntax#} can participate 2254 in a {#link|@bitCast#} or a {#link|@ptrCast#} to reinterpret memory. 2255 This even works at {#link|comptime#}: 2256 </p> 2257 {#code|test_packed_structs.zig#} 2258 <p> 2259 The backing integer can be inferred or explicitly provided. When 2260 inferred, it will be unsigned. When explicitly provided, its bit width 2261 will be enforced at compile time to exactly match the total bit width of 2262 the fields: 2263 </p> 2264 {#code|test_missized_packed_struct.zig#} 2265 2266 <p> 2267 Zig allows the address to be taken of a non-byte-aligned field: 2268 </p> 2269 {#code|test_pointer_to_non-byte_aligned_field.zig#} 2270 2271 <p> 2272 However, the pointer to a non-byte-aligned field has special properties and cannot 2273 be passed when a normal pointer is expected: 2274 </p> 2275 {#code|test_misaligned_pointer.zig#} 2276 2277 <p> 2278 In this case, the function {#syntax#}bar{#endsyntax#} cannot be called because the pointer 2279 to the non-ABI-aligned field mentions the bit offset, but the function expects an ABI-aligned pointer. 2280 </p> 2281 <p> 2282 Pointers to non-ABI-aligned fields share the same address as the other fields within their host integer: 2283 </p> 2284 {#code|test_packed_struct_field_address.zig#} 2285 2286 <p> 2287 This can be observed with {#link|@bitOffsetOf#} and {#link|offsetOf#}: 2288 </p> 2289 {#code|test_bitOffsetOf_offsetOf.zig#} 2290 2291 <p> 2292 Packed structs have the same alignment as their backing integer, however, overaligned 2293 pointers to packed structs can override this: 2294 </p> 2295 {#code|test_overaligned_packed_struct.zig#} 2296 2297 <p> 2298 It's also possible to set alignment of struct fields: 2299 </p> 2300 {#code|test_aligned_struct_fields.zig#} 2301 2302 <p> 2303 Equating packed structs results in a comparison of the backing integer, 2304 and only works for the {#syntax#}=={#endsyntax#} and {#syntax#}!={#endsyntax#} {#link|Operators#}. 2305 </p> 2306 {#code|test_packed_struct_equality.zig#} 2307 2308 <p> 2309 Field access and assignment can be understood as shorthand for bitshifts 2310 on the backing integer. These operations are not {#link|atomic|Atomics#}, 2311 so beware using field access syntax when combined with memory-mapped 2312 input-output (MMIO). Instead of field access on {#link|volatile#} {#link|Pointers#}, 2313 construct a fully-formed new value first, then write that value to the volatile pointer. 2314 </p> 2315 {#code|packed_struct_mmio.zig#} 2316 {#header_close#} 2317 2318 {#header_open|Struct Naming#} 2319 <p>Since all structs are anonymous, Zig infers the type name based on a few rules.</p> 2320 <ul> 2321 <li>If the struct is in the initialization expression of a variable, it gets named after 2322 that variable.</li> 2323 <li>If the struct is in the {#syntax#}return{#endsyntax#} expression, it gets named after 2324 the function it is returning from, with the parameter values serialized.</li> 2325 <li>Otherwise, the struct gets a name such as <code>(filename.funcname__struct_ID)</code>.</li> 2326 <li>If the struct is declared inside another struct, it gets named after both the parent 2327 struct and the name inferred by the previous rules, separated by a dot.</li> 2328 </ul> 2329 {#code|struct_name.zig#} 2330 2331 {#header_close#} 2332 2333 {#header_open|Anonymous Struct Literals#} 2334 <p> 2335 Zig allows omitting the struct type of a literal. When the result is {#link|coerced|Type Coercion#}, 2336 the struct literal will directly instantiate the {#link|result location|Result Location Semantics#}, 2337 with no copy: 2338 </p> 2339 {#code|test_struct_result.zig#} 2340 2341 <p> 2342 The struct type can be inferred. Here the {#link|result location|Result Location Semantics#} 2343 does not include a type, and so Zig infers the type: 2344 </p> 2345 {#code|test_anonymous_struct.zig#} 2346 2347 {#header_close#} 2348 2349 {#header_open|Tuples#} 2350 <p> 2351 Anonymous structs can be created without specifying field names, and are referred to as "tuples". An empty tuple looks like <code>.{}</code> and can be seen in one of the {#link|Hello World examples|Hello World#}. 2352 </p> 2353 <p> 2354 The fields are implicitly named using numbers starting from 0. Because their names are integers, 2355 they cannot be accessed with {#syntax#}.{#endsyntax#} syntax without also wrapping them in 2356 {#syntax#}@""{#endsyntax#}. Names inside {#syntax#}@""{#endsyntax#} are always recognised as 2357 {#link|identifiers|Identifiers#}. 2358 </p> 2359 <p> 2360 Like arrays, tuples have a .len field, can be indexed (provided the index is comptime-known) 2361 and work with the ++ and ** operators. They can also be iterated over with {#link|inline for#}. 2362 </p> 2363 {#code|test_tuples.zig#} 2364 2365 {#header_open|Destructuring Tuples#} 2366 <p> 2367 Tuples can be {#link|destructured|Destructuring#}. 2368 </p> 2369 <p> 2370 Tuple destructuring is helpful for returning multiple values from a block: 2371 </p> 2372 {#code|destructuring_block.zig#} 2373 2374 <p> 2375 Tuple destructuring is helpful for dealing with functions and built-ins that return multiple values 2376 as a tuple: 2377 </p> 2378 {#code|destructuring_return_value.zig#} 2379 2380 {#see_also|Destructuring|Destructuring Arrays|Destructuring Vectors#} 2381 {#header_close#} 2382 {#header_close#} 2383 {#see_also|comptime|@fieldParentPtr#} 2384 {#header_close#} 2385 {#header_open|enum#} 2386 {#code|test_enums.zig#} 2387 2388 {#see_also|@typeInfo|@tagName|@sizeOf#} 2389 2390 {#header_open|extern enum#} 2391 <p> 2392 By default, enums are not guaranteed to be compatible with the C ABI: 2393 </p> 2394 {#code|enum_export_error.zig#} 2395 2396 <p> 2397 For a C-ABI-compatible enum, provide an explicit tag type to 2398 the enum: 2399 </p> 2400 {#code|enum_export.zig#} 2401 2402 {#header_close#} 2403 2404 {#header_open|Enum Literals#} 2405 <p> 2406 Enum literals allow specifying the name of an enum field without specifying the enum type: 2407 </p> 2408 {#code|test_enum_literals.zig#} 2409 2410 {#header_close#} 2411 2412 {#header_open|Non-exhaustive enum#} 2413 <p> 2414 A non-exhaustive enum can be created by adding a trailing {#syntax#}_{#endsyntax#} field. 2415 The enum must specify a tag type and cannot consume every enumeration value. 2416 </p> 2417 <p> 2418 {#link|@enumFromInt#} on a non-exhaustive enum involves the safety semantics 2419 of {#link|@intCast#} to the integer tag type, but beyond that always results in 2420 a well-defined enum value. 2421 </p> 2422 <p> 2423 A switch on a non-exhaustive enum can include a {#syntax#}_{#endsyntax#} prong as an alternative to an {#syntax#}else{#endsyntax#} prong. 2424 With a {#syntax#}_{#endsyntax#} prong the compiler errors if all the known tag names are not handled by the switch. 2425 </p> 2426 {#code|test_switch_non-exhaustive.zig#} 2427 2428 {#header_close#} 2429 {#header_close#} 2430 2431 {#header_open|union#} 2432 <p> 2433 A bare {#syntax#}union{#endsyntax#} defines a set of possible types that a value 2434 can be as a list of fields. Only one field can be active at a time. 2435 The in-memory representation of bare unions is not guaranteed. 2436 Bare unions cannot be used to reinterpret memory. For that, use {#link|@ptrCast#}, 2437 or use an {#link|extern union#} or a {#link|packed union#} which have 2438 guaranteed in-memory layout. 2439 {#link|Accessing the non-active field|Wrong Union Field Access#} is 2440 safety-checked {#link|Illegal Behavior#}: 2441 </p> 2442 {#code|test_wrong_union_access.zig#} 2443 2444 <p>You can activate another field by assigning the entire union:</p> 2445 {#code|test_simple_union.zig#} 2446 2447 <p> 2448 In order to use {#link|switch#} with a union, it must be a {#link|Tagged union#}. 2449 </p> 2450 <p> 2451 To initialize a union when the tag is a {#link|comptime#}-known name, see {#link|@unionInit#}. 2452 </p> 2453 2454 {#header_open|Tagged union#} 2455 <p>Unions can be declared with an enum tag type. 2456 This turns the union into a <em>tagged</em> union, which makes it eligible 2457 to use with {#link|switch#} expressions. 2458 Tagged unions coerce to their tag type: {#link|Type Coercion: Unions and Enums#}. 2459 </p> 2460 {#code|test_tagged_union.zig#} 2461 2462 <p>In order to modify the payload of a tagged union in a switch expression, 2463 place a {#syntax#}*{#endsyntax#} before the variable name to make it a pointer: 2464 </p> 2465 {#code|test_switch_modify_tagged_union.zig#} 2466 2467 <p> 2468 Unions can be made to infer the enum tag type. 2469 Further, unions can have methods just like structs and enums. 2470 </p> 2471 {#code|test_union_method.zig#} 2472 2473 <p> 2474 Unions with inferred enum tag types can also assign ordinal values to their inferred tag. 2475 This requires the tag to specify an explicit integer type. 2476 {#link|@intFromEnum#} can be used to access the ordinal value corresponding to the active field. 2477 </p> 2478 {#code|test_tagged_union_with_tag_values.zig#} 2479 2480 <p> 2481 {#link|@tagName#} can be used to return a {#link|comptime#} 2482 {#syntax#}[:0]const u8{#endsyntax#} value representing the field name: 2483 </p> 2484 {#code|test_tagName.zig#} 2485 2486 {#header_close#} 2487 2488 {#header_open|extern union#} 2489 <p> 2490 An {#syntax#}extern union{#endsyntax#} has memory layout guaranteed to be compatible with 2491 the target C ABI. 2492 </p> 2493 {#see_also|extern struct#} 2494 {#header_close#} 2495 2496 {#header_open|packed union#} 2497 <p>A {#syntax#}packed union{#endsyntax#} has well-defined in-memory layout and is eligible 2498 to be in a {#link|packed struct#}.</p> 2499 {#header_close#} 2500 2501 {#header_open|Anonymous Union Literals#} 2502 <p>{#link|Anonymous Struct Literals#} syntax can be used to initialize unions without specifying 2503 the type:</p> 2504 {#code|test_anonymous_union.zig#} 2505 2506 {#header_close#} 2507 2508 {#header_close#} 2509 2510 {#header_open|opaque#} 2511 <p> 2512 {#syntax#}opaque {}{#endsyntax#} declares a new type with an unknown (but non-zero) size and alignment. 2513 It can contain declarations the same as {#link|structs|struct#}, {#link|unions|union#}, 2514 and {#link|enums|enum#}. 2515 </p> 2516 <p> 2517 This is typically used for type safety when interacting with C code that does not expose struct details. 2518 Example: 2519 </p> 2520 {#code|test_opaque.zig#} 2521 2522 {#header_close#} 2523 2524 {#header_open|Blocks#} 2525 <p> 2526 Blocks are used to limit the scope of variable declarations: 2527 </p> 2528 {#code|test_blocks.zig#} 2529 2530 <p>Blocks are expressions. When labeled, {#syntax#}break{#endsyntax#} can be used 2531 to return a value from the block: 2532 </p> 2533 {#code|test_labeled_break.zig#} 2534 2535 <p>Here, {#syntax#}blk{#endsyntax#} can be any name.</p> 2536 {#see_also|Labeled while|Labeled for#} 2537 2538 {#header_open|Shadowing#} 2539 <p>{#link|Identifiers#} are never allowed to "hide" other identifiers by using the same name:</p> 2540 {#code|test_shadowing.zig#} 2541 2542 <p> 2543 Because of this, when you read Zig code you can always rely on an identifier to consistently mean 2544 the same thing within the scope it is defined. Note that you can, however, use the same name if 2545 the scopes are separate: 2546 </p> 2547 {#code|test_scopes.zig#} 2548 2549 {#header_close#} 2550 2551 {#header_open|Empty Blocks#} 2552 <p>An empty block is equivalent to {#syntax#}void{}{#endsyntax#}:</p> 2553 {#code|test_empty_block.zig#} 2554 2555 {#header_close#} 2556 {#header_close#} 2557 2558 {#header_open|switch#} 2559 {#code|test_switch.zig#} 2560 2561 <p> 2562 {#syntax#}switch{#endsyntax#} can be used to capture the field values 2563 of a {#link|Tagged union#}. Modifications to the field values can be 2564 done by placing a {#syntax#}*{#endsyntax#} before the capture variable name, 2565 turning it into a pointer. 2566 </p> 2567 {#code|test_switch_tagged_union.zig#} 2568 2569 {#see_also|comptime|enum|@compileError|Compile Variables#} 2570 2571 {#header_open|Exhaustive Switching#} 2572 <p> 2573 When a {#syntax#}switch{#endsyntax#} expression does not have an {#syntax#}else{#endsyntax#} clause, 2574 it must exhaustively list all the possible values. Failure to do so is a compile error: 2575 </p> 2576 {#code|test_unhandled_enumeration_value.zig#} 2577 2578 {#header_close#} 2579 2580 {#header_open|Switching with Enum Literals#} 2581 <p> 2582 {#link|Enum Literals#} can be useful to use with {#syntax#}switch{#endsyntax#} to avoid 2583 repetitively specifying {#link|enum#} or {#link|union#} types: 2584 </p> 2585 {#code|test_exhaustive_switch.zig#} 2586 2587 {#header_close#} 2588 2589 {#header_open|Labeled switch#} 2590 <p> 2591 When a switch statement is labeled, it can be referenced from a 2592 {#syntax#}break{#endsyntax#} or {#syntax#}continue{#endsyntax#}. 2593 {#syntax#}break{#endsyntax#} will return a value from the {#syntax#} 2594 switch{#endsyntax#}. 2595 </p> 2596 <p> 2597 A {#syntax#}continue{#endsyntax#} targeting a switch must have an 2598 operand. When executed, it will jump to the matching prong, as if the 2599 {#syntax#}switch{#endsyntax#} were executed again with the {#syntax#} 2600 continue{#endsyntax#}'s operand replacing the initial switch value. 2601 </p> 2602 2603 {#code|test_switch_continue.zig#} 2604 2605 <p> 2606 Semantically, this is equivalent to the following loop: 2607 </p> 2608 {#code|test_switch_continue_equivalent.zig#} 2609 2610 <p> 2611 This can improve clarity of (for example) state machines, where the syntax {#syntax#}continue :sw .next_state{#endsyntax#} is unambiguous, explicit, and immediately understandable. 2612 </p> 2613 <p> 2614 However, the motivating example is a switch on each element of an array, where using a single switch can improve clarity and performance: 2615 </p> 2616 {#code|test_switch_dispatch_loop.zig#} 2617 2618 <p> 2619 If the operand to {#syntax#}continue{#endsyntax#} is 2620 {#link|comptime#}-known, then it can be lowered to an unconditional branch 2621 to the relevant case. Such a branch is perfectly predicted, and hence 2622 typically very fast to execute. 2623 </p> 2624 2625 <p> 2626 If the operand is runtime-known, each {#syntax#}continue{#endsyntax#} can 2627 embed a conditional branch inline (ideally through a jump table), which 2628 allows a CPU to predict its target independently of any other prong. A 2629 loop-based lowering would force every branch through the same dispatch 2630 point, hindering branch prediction. 2631 </p> 2632 2633 2634 {#header_close#} 2635 2636 {#header_open|Inline Switch Prongs#} 2637 <p> 2638 Switch prongs can be marked as {#syntax#}inline{#endsyntax#} to generate 2639 the prong's body for each possible value it could have, making the 2640 captured value {#link|comptime#}. 2641 </p> 2642 {#code|test_inline_switch.zig#} 2643 2644 <p>The {#syntax#}inline{#endsyntax#} keyword may also be combined with ranges:</p> 2645 {#code|inline_prong_range.zig#} 2646 2647 <p> 2648 {#syntax#}inline else{#endsyntax#} prongs can be used as a type safe 2649 alternative to {#syntax#}inline for{#endsyntax#} loops: 2650 </p> 2651 {#code|test_inline_else.zig#} 2652 2653 <p> 2654 When using an inline prong switching on an union an additional 2655 capture can be used to obtain the union's enum tag value. 2656 </p> 2657 {#code|test_inline_switch_union_tag.zig#} 2658 2659 {#see_also|inline while|inline for#} 2660 {#header_close#} 2661 {#header_close#} 2662 2663 {#header_open|while#} 2664 <p> 2665 A while loop is used to repeatedly execute an expression until 2666 some condition is no longer true. 2667 </p> 2668 {#code|test_while.zig#} 2669 2670 <p> 2671 Use {#syntax#}break{#endsyntax#} to exit a while loop early. 2672 </p> 2673 {#code|test_while_break.zig#} 2674 2675 <p> 2676 Use {#syntax#}continue{#endsyntax#} to jump back to the beginning of the loop. 2677 </p> 2678 {#code|test_while_continue.zig#} 2679 2680 <p> 2681 While loops support a continue expression which is executed when the loop 2682 is continued. The {#syntax#}continue{#endsyntax#} keyword respects this expression. 2683 </p> 2684 {#code|test_while_continue_expression.zig#} 2685 2686 <p> 2687 While loops are expressions. The result of the expression is the 2688 result of the {#syntax#}else{#endsyntax#} clause of a while loop, which is executed when 2689 the condition of the while loop is tested as false. 2690 </p> 2691 <p> 2692 {#syntax#}break{#endsyntax#}, like {#syntax#}return{#endsyntax#}, accepts a value 2693 parameter. This is the result of the {#syntax#}while{#endsyntax#} expression. 2694 When you {#syntax#}break{#endsyntax#} from a while loop, the {#syntax#}else{#endsyntax#} branch is not 2695 evaluated. 2696 </p> 2697 {#code|test_while_else.zig#} 2698 2699 {#header_open|Labeled while#} 2700 <p>When a {#syntax#}while{#endsyntax#} loop is labeled, it can be referenced from a {#syntax#}break{#endsyntax#} 2701 or {#syntax#}continue{#endsyntax#} from within a nested loop:</p> 2702 {#code|test_while_nested_break.zig#} 2703 2704 {#header_close#} 2705 {#header_open|while with Optionals#} 2706 <p> 2707 Just like {#link|if#} expressions, while loops can take an optional as the 2708 condition and capture the payload. When {#link|null#} is encountered the loop 2709 exits. 2710 </p> 2711 <p> 2712 When the {#syntax#}|x|{#endsyntax#} syntax is present on a {#syntax#}while{#endsyntax#} expression, 2713 the while condition must have an {#link|Optional Type#}. 2714 </p> 2715 <p> 2716 The {#syntax#}else{#endsyntax#} branch is allowed on optional iteration. In this case, it will 2717 be executed on the first null value encountered. 2718 </p> 2719 {#code|test_while_null_capture.zig#} 2720 2721 {#header_close#} 2722 2723 {#header_open|while with Error Unions#} 2724 <p> 2725 Just like {#link|if#} expressions, while loops can take an error union as 2726 the condition and capture the payload or the error code. When the 2727 condition results in an error code the else branch is evaluated and 2728 the loop is finished. 2729 </p> 2730 <p> 2731 When the {#syntax#}else |x|{#endsyntax#} syntax is present on a {#syntax#}while{#endsyntax#} expression, 2732 the while condition must have an {#link|Error Union Type#}. 2733 </p> 2734 {#code|test_while_error_capture.zig#} 2735 2736 {#header_close#} 2737 2738 {#header_open|inline while#} 2739 <p> 2740 While loops can be inlined. This causes the loop to be unrolled, which 2741 allows the code to do some things which only work at compile time, 2742 such as use types as first class values. 2743 </p> 2744 {#code|test_inline_while.zig#} 2745 2746 <p> 2747 It is recommended to use {#syntax#}inline{#endsyntax#} loops only for one of these reasons: 2748 </p> 2749 <ul> 2750 <li>You need the loop to execute at {#link|comptime#} for the semantics to work.</li> 2751 <li> 2752 You have a benchmark to prove that forcibly unrolling the loop in this way is measurably faster. 2753 </li> 2754 </ul> 2755 {#header_close#} 2756 {#see_also|if|Optionals|Errors|comptime|unreachable#} 2757 {#header_close#} 2758 {#header_open|for#} 2759 {#code|test_for.zig#} 2760 2761 {#header_open|Labeled for#} 2762 <p>When a {#syntax#}for{#endsyntax#} loop is labeled, it can be referenced from a {#syntax#}break{#endsyntax#} 2763 or {#syntax#}continue{#endsyntax#} from within a nested loop:</p> 2764 {#code|test_for_nested_break.zig#} 2765 2766 {#header_close#} 2767 {#header_open|inline for#} 2768 <p> 2769 For loops can be inlined. This causes the loop to be unrolled, which 2770 allows the code to do some things which only work at compile time, 2771 such as use types as first class values. 2772 The capture value and iterator value of inlined for loops are 2773 compile-time known. 2774 </p> 2775 {#code|test_inline_for.zig#} 2776 2777 <p> 2778 It is recommended to use {#syntax#}inline{#endsyntax#} loops only for one of these reasons: 2779 </p> 2780 <ul> 2781 <li>You need the loop to execute at {#link|comptime#} for the semantics to work.</li> 2782 <li> 2783 You have a benchmark to prove that forcibly unrolling the loop in this way is measurably faster. 2784 </li> 2785 </ul> 2786 {#header_close#} 2787 {#see_also|while|comptime|Arrays|Slices#} 2788 {#header_close#} 2789 {#header_open|if#} 2790 {#code|test_if.zig#} 2791 2792 {#header_open|if with Optionals#} 2793 2794 {#code|test_if_optionals.zig#} 2795 2796 {#header_close#} 2797 {#see_also|Optionals|Errors#} 2798 {#header_close#} 2799 {#header_open|defer#} 2800 <p>Executes an expression unconditionally at scope exit.</p> 2801 {#code|test_defer.zig#} 2802 2803 <p>Defer expressions are evaluated in reverse order.</p> 2804 {#code|defer_unwind.zig#} 2805 2806 <p>Inside a defer expression the return statement is not allowed.</p> 2807 {#code|test_invalid_defer.zig#} 2808 2809 {#see_also|Errors#} 2810 {#header_close#} 2811 {#header_open|unreachable#} 2812 <p> 2813 In {#link|Debug#} and {#link|ReleaseSafe#} mode 2814 {#syntax#}unreachable{#endsyntax#} emits a call to {#syntax#}panic{#endsyntax#} with the message <code>reached unreachable code</code>. 2815 </p> 2816 <p> 2817 In {#link|ReleaseFast#} and {#link|ReleaseSmall#} mode, the optimizer uses the assumption that {#syntax#}unreachable{#endsyntax#} code 2818 will never be hit to perform optimizations. 2819 </p> 2820 {#header_open|Basics#} 2821 {#code|test_unreachable.zig#} 2822 2823 <p>In fact, this is how {#syntax#}std.debug.assert{#endsyntax#} is implemented:</p> 2824 {#code|test_assertion_failure.zig#} 2825 2826 {#header_close#} 2827 {#header_open|At Compile-Time#} 2828 {#code|test_comptime_unreachable.zig#} 2829 2830 {#see_also|Zig Test|Build Mode|comptime#} 2831 {#header_close#} 2832 {#header_close#} 2833 {#header_open|noreturn#} 2834 <p> 2835 {#syntax#}noreturn{#endsyntax#} is the type of: 2836 </p> 2837 <ul> 2838 <li>{#syntax#}break{#endsyntax#}</li> 2839 <li>{#syntax#}continue{#endsyntax#}</li> 2840 <li>{#syntax#}return{#endsyntax#}</li> 2841 <li>{#syntax#}unreachable{#endsyntax#}</li> 2842 <li>{#syntax#}while (true) {}{#endsyntax#}</li> 2843 </ul> 2844 <p>When resolving types together, such as {#syntax#}if{#endsyntax#} clauses or {#syntax#}switch{#endsyntax#} prongs, 2845 the {#syntax#}noreturn{#endsyntax#} type is compatible with every other type. Consider: 2846 </p> 2847 {#code|test_noreturn.zig#} 2848 2849 <p>Another use case for {#syntax#}noreturn{#endsyntax#} is the {#syntax#}exit{#endsyntax#} function:</p> 2850 {#code|test_noreturn_from_exit.zig#} 2851 2852 {#header_close#} 2853 2854 {#header_open|Functions#} 2855 {#code|test_functions.zig#} 2856 2857 <p>There is a difference between a function <em>body</em> and a function <em>pointer</em>. 2858 Function bodies are {#link|comptime#}-only types while function {#link|Pointers#} may be 2859 runtime-known.</p> 2860 {#header_open|Pass-by-value Parameters#} 2861 <p> 2862 Primitive types such as {#link|Integers#} and {#link|Floats#} passed as parameters 2863 are copied, and then the copy is available in the function body. This is called "passing by value". 2864 Copying a primitive type is essentially free and typically involves nothing more than 2865 setting a register. 2866 </p> 2867 <p> 2868 Structs, unions, and arrays can sometimes be more efficiently passed as a reference, since a copy 2869 could be arbitrarily expensive depending on the size. When these types are passed 2870 as parameters, Zig may choose to copy and pass by value, or pass by reference, whichever way 2871 Zig decides will be faster. This is made possible, in part, by the fact that parameters are immutable. 2872 </p> 2873 {#code|test_pass_by_reference_or_value.zig#} 2874 2875 <p> 2876 For extern functions, Zig follows the C ABI for passing structs and unions by value. 2877 </p> 2878 {#header_close#} 2879 {#header_open|Function Parameter Type Inference#} 2880 <p> 2881 Function parameters can be declared with {#syntax#}anytype{#endsyntax#} in place of the type. 2882 In this case the parameter types will be inferred when the function is called. 2883 Use {#link|@TypeOf#} and {#link|@typeInfo#} to get information about the inferred type. 2884 </p> 2885 {#code|test_fn_type_inference.zig#} 2886 2887 2888 {#header_close#} 2889 2890 {#header_open|inline fn#} 2891 <p> 2892 Adding the {#syntax#}inline{#endsyntax#} keyword to a function definition makes that 2893 function become <em>semantically inlined</em> at the callsite. This is 2894 not a hint to be possibly observed by optimization passes, but has 2895 implications on the types and values involved in the function call. 2896 </p> 2897 <p> 2898 Unlike normal function calls, arguments at an inline function callsite which are 2899 compile-time known are treated as {#link|Compile Time Parameters#}. This can potentially 2900 propagate all the way to the return value: 2901 </p> 2902 {#code|inline_call.zig#} 2903 2904 <p>If {#syntax#}inline{#endsyntax#} is removed, the test fails with the compile error 2905 instead of passing.</p> 2906 <p>It is generally better to let the compiler decide when to inline a 2907 function, except for these scenarios:</p> 2908 <ul> 2909 <li>To change how many stack frames are in the call stack, for debugging purposes.</li> 2910 <li>To force comptime-ness of the arguments to propagate to the return value of the function, as in the above example.</li> 2911 <li>Real world performance measurements demand it.</li> 2912 </ul> 2913 <p>Note that {#syntax#}inline{#endsyntax#} actually <em>restricts</em> 2914 what the compiler is allowed to do. This can harm binary size, 2915 compilation speed, and even runtime performance.</p> 2916 {#header_close#} 2917 2918 {#header_open|Function Reflection#} 2919 {#code|test_fn_reflection.zig#} 2920 2921 {#header_close#} 2922 {#header_close#} 2923 {#header_open|Errors#} 2924 {#header_open|Error Set Type#} 2925 <p> 2926 An error set is like an {#link|enum#}. 2927 However, each error name across the entire compilation gets assigned an unsigned integer 2928 greater than 0. You are allowed to declare the same error name more than once, and if you do, it 2929 gets assigned the same integer value. 2930 </p> 2931 <p> 2932 The error set type defaults to a {#syntax#}u16{#endsyntax#}, though if the maximum number of distinct 2933 error values is provided via the <kbd>--error-limit [num]</kbd> command line parameter an integer type 2934 with the minimum number of bits required to represent all of the error values will be used. 2935 </p> 2936 <p> 2937 You can {#link|coerce|Type Coercion#} an error from a subset to a superset: 2938 </p> 2939 {#code|test_coerce_error_subset_to_superset.zig#} 2940 2941 <p> 2942 But you cannot {#link|coerce|Type Coercion#} an error from a superset to a subset: 2943 </p> 2944 {#code|test_coerce_error_superset_to_subset.zig#} 2945 2946 <p> 2947 There is a shortcut for declaring an error set with only 1 value, and then getting that value: 2948 </p> 2949 {#code|single_value_error_set_shortcut.zig#} 2950 2951 <p>This is equivalent to:</p> 2952 {#code|single_value_error_set.zig#} 2953 2954 <p> 2955 This becomes useful when using {#link|Inferred Error Sets#}. 2956 </p> 2957 {#header_open|The Global Error Set#} 2958 <p>{#syntax#}anyerror{#endsyntax#} refers to the global error set. 2959 This is the error set that contains all errors in the entire compilation unit, i.e. it is the union of all other error sets. 2960 </p> 2961 <p> 2962 You can {#link|coerce|Type Coercion#} any error set to the global one, and you can explicitly 2963 cast an error of the global error set to a non-global one. This inserts a language-level 2964 assert to make sure the error value is in fact in the destination error set. 2965 </p> 2966 <p> 2967 The global error set should generally be avoided because it prevents the 2968 compiler from knowing what errors are possible at compile-time. Knowing 2969 the error set at compile-time is better for generated documentation and 2970 helpful error messages, such as forgetting a possible error value in a {#link|switch#}. 2971 </p> 2972 {#header_close#} 2973 {#header_close#} 2974 {#header_open|Error Union Type#} 2975 <p> 2976 An error set type and normal type can be combined with the {#syntax#}!{#endsyntax#} 2977 binary operator to form an error union type. You are likely to use an 2978 error union type more often than an error set type by itself. 2979 </p> 2980 <p> 2981 Here is a function to parse a string into a 64-bit integer: 2982 </p> 2983 {#code|error_union_parsing_u64.zig#} 2984 2985 <p> 2986 Notice the return type is {#syntax#}!u64{#endsyntax#}. This means that the function 2987 either returns an unsigned 64 bit integer, or an error. We left off the error set 2988 to the left of the {#syntax#}!{#endsyntax#}, so the error set is inferred. 2989 </p> 2990 <p> 2991 Within the function definition, you can see some return statements that return 2992 an error, and at the bottom a return statement that returns a {#syntax#}u64{#endsyntax#}. 2993 Both types {#link|coerce|Type Coercion#} to {#syntax#}anyerror!u64{#endsyntax#}. 2994 </p> 2995 <p> 2996 What it looks like to use this function varies depending on what you're 2997 trying to do. One of the following: 2998 </p> 2999 <ul> 3000 <li>You want to provide a default value if it returned an error.</li> 3001 <li>If it returned an error then you want to return the same error.</li> 3002 <li>You know with complete certainty it will not return an error, so want to unconditionally unwrap it.</li> 3003 <li>You want to take a different action for each possible error.</li> 3004 </ul> 3005 {#header_open|catch#} 3006 <p>If you want to provide a default value, you can use the {#syntax#}catch{#endsyntax#} binary operator:</p> 3007 {#code|catch.zig#} 3008 3009 <p> 3010 In this code, {#syntax#}number{#endsyntax#} will be equal to the successfully parsed string, or 3011 a default value of 13. The type of the right hand side of the binary {#syntax#}catch{#endsyntax#} operator must 3012 match the unwrapped error union type, or be of type {#syntax#}noreturn{#endsyntax#}. 3013 </p> 3014 <p> 3015 If you want to provide a default value with 3016 {#syntax#}catch{#endsyntax#} after performing some logic, you 3017 can combine {#syntax#}catch{#endsyntax#} with named {#link|Blocks#}: 3018 </p> 3019 {#code|handle_error_with_catch_block.zig.zig#} 3020 3021 {#header_close#} 3022 {#header_open|try#} 3023 <p>Let's say you wanted to return the error if you got one, otherwise continue with the 3024 function logic:</p> 3025 {#code|catch_err_return.zig#} 3026 3027 <p> 3028 There is a shortcut for this. The {#syntax#}try{#endsyntax#} expression: 3029 </p> 3030 {#code|try.zig#} 3031 3032 <p> 3033 {#syntax#}try{#endsyntax#} evaluates an error union expression. If it is an error, it returns 3034 from the current function with the same error. Otherwise, the expression results in 3035 the unwrapped value. 3036 </p> 3037 {#header_close#} 3038 <p> 3039 Maybe you know with complete certainty that an expression will never be an error. 3040 In this case you can do this: 3041 </p> 3042 {#syntax#}const number = parseU64("1234", 10) catch unreachable;{#endsyntax#} 3043 <p> 3044 Here we know for sure that "1234" will parse successfully. So we put the 3045 {#syntax#}unreachable{#endsyntax#} value on the right hand side. 3046 {#syntax#}unreachable{#endsyntax#} invokes safety-checked {#link|Illegal Behavior#}, so 3047 in {#link|Debug#} and {#link|ReleaseSafe#}, triggers a safety panic by default. So, while 3048 we're debugging the application, if there <em>was</em> a surprise error here, the application 3049 would crash appropriately. 3050 </p> 3051 <p> 3052 You may want to take a different action for every situation. For that, we combine 3053 the {#link|if#} and {#link|switch#} expression: 3054 </p> 3055 {#syntax_block|zig|handle_all_error_scenarios.zig#} 3056 fn doAThing(str: []u8) void { 3057 if (parseU64(str, 10)) |number| { 3058 doSomethingWithNumber(number); 3059 } else |err| switch (err) { 3060 error.Overflow => { 3061 // handle overflow... 3062 }, 3063 // we promise that InvalidChar won't happen (or crash in debug mode if it does) 3064 error.InvalidChar => unreachable, 3065 } 3066 } 3067 {#end_syntax_block#} 3068 <p> 3069 Finally, you may want to handle only some errors. For that, you can capture the unhandled 3070 errors in the {#syntax#}else{#endsyntax#} case, which now contains a narrower error set: 3071 </p> 3072 {#syntax_block|zig|handle_some_error_scenarios.zig#} 3073 fn doAnotherThing(str: []u8) error{InvalidChar}!void { 3074 if (parseU64(str, 10)) |number| { 3075 doSomethingWithNumber(number); 3076 } else |err| switch (err) { 3077 error.Overflow => { 3078 // handle overflow... 3079 }, 3080 else => |leftover_err| return leftover_err, 3081 } 3082 } 3083 {#end_syntax_block#} 3084 <p> 3085 You must use the variable capture syntax. If you don't need the 3086 variable, you can capture with {#syntax#}_{#endsyntax#} and avoid the 3087 {#syntax#}switch{#endsyntax#}. 3088 </p> 3089 {#syntax_block|zig|handle_no_error_scenarios.zig#} 3090 fn doADifferentThing(str: []u8) void { 3091 if (parseU64(str, 10)) |number| { 3092 doSomethingWithNumber(number); 3093 } else |_| { 3094 // do as you'd like 3095 } 3096 } 3097 {#end_syntax_block#} 3098 {#header_open|errdefer#} 3099 <p> 3100 The other component to error handling is defer statements. 3101 In addition to an unconditional {#link|defer#}, Zig has {#syntax#}errdefer{#endsyntax#}, 3102 which evaluates the deferred expression on block exit path if and only if 3103 the function returned with an error from the block. 3104 </p> 3105 <p> 3106 Example: 3107 </p> 3108 {#syntax_block|zig|errdefer_example.zig#} 3109 fn createFoo(param: i32) !Foo { 3110 const foo = try tryToAllocateFoo(); 3111 // now we have allocated foo. we need to free it if the function fails. 3112 // but we want to return it if the function succeeds. 3113 errdefer deallocateFoo(foo); 3114 3115 const tmp_buf = allocateTmpBuffer() orelse return error.OutOfMemory; 3116 // tmp_buf is truly a temporary resource, and we for sure want to clean it up 3117 // before this block leaves scope 3118 defer deallocateTmpBuffer(tmp_buf); 3119 3120 if (param > 1337) return error.InvalidParam; 3121 3122 // here the errdefer will not run since we're returning success from the function. 3123 // but the defer will run! 3124 return foo; 3125 } 3126 {#end_syntax_block#} 3127 <p> 3128 The neat thing about this is that you get robust error handling without 3129 the verbosity and cognitive overhead of trying to make sure every exit path 3130 is covered. The deallocation code is always directly following the allocation code. 3131 </p> 3132 <p> 3133 The {#syntax#}errdefer{#endsyntax#} statement can optionally capture the error: 3134 </p> 3135 {#code|test_errdefer_capture.zig#} 3136 {#header_close#} 3137 <p> 3138 A couple of other tidbits about error handling: 3139 </p> 3140 <ul> 3141 <li>These primitives give enough expressiveness that it's completely practical 3142 to have failing to check for an error be a compile error. If you really want 3143 to ignore the error, you can add {#syntax#}catch unreachable{#endsyntax#} and 3144 get the added benefit of crashing in Debug and ReleaseSafe modes if your assumption was wrong. 3145 </li> 3146 <li> 3147 Since Zig understands error types, it can pre-weight branches in favor of 3148 errors not occurring. Just a small optimization benefit that is not available 3149 in other languages. 3150 </li> 3151 </ul> 3152 {#see_also|defer|if|switch#} 3153 3154 <p>An error union is created with the {#syntax#}!{#endsyntax#} binary operator. 3155 You can use compile-time reflection to access the child type of an error union:</p> 3156 {#code|test_error_union.zig#} 3157 3158 {#header_open|Merging Error Sets#} 3159 <p> 3160 Use the {#syntax#}||{#endsyntax#} operator to merge two error sets together. The resulting 3161 error set contains the errors of both error sets. Doc comments from the left-hand 3162 side override doc comments from the right-hand side. In this example, the doc 3163 comments for {#syntax#}C.PathNotFound{#endsyntax#} is <code>A doc comment</code>. 3164 </p> 3165 <p> 3166 This is especially useful for functions which return different error sets depending 3167 on {#link|comptime#} branches. For example, the Zig standard library uses 3168 {#syntax#}LinuxFileOpenError || WindowsFileOpenError{#endsyntax#} for the error set of opening 3169 files. 3170 </p> 3171 {#code|test_merging_error_sets.zig#} 3172 3173 {#header_close#} 3174 {#header_open|Inferred Error Sets#} 3175 <p> 3176 Because many functions in Zig return a possible error, Zig supports inferring the error set. 3177 To infer the error set for a function, prepend the {#syntax#}!{#endsyntax#} operator to the function’s return type, like {#syntax#}!T{#endsyntax#}: 3178 </p> 3179 {#code|test_inferred_error_sets.zig#} 3180 3181 <p> 3182 When a function has an inferred error set, that function becomes generic and thus it becomes 3183 trickier to do certain things with it, such as obtain a function pointer, or have an error 3184 set that is consistent across different build targets. Additionally, inferred error sets 3185 are incompatible with recursion. 3186 </p> 3187 <p> 3188 In these situations, it is recommended to use an explicit error set. You can generally start 3189 with an empty error set and let compile errors guide you toward completing the set. 3190 </p> 3191 <p> 3192 These limitations may be overcome in a future version of Zig. 3193 </p> 3194 {#header_close#} 3195 {#header_close#} 3196 {#header_open|Error Return Traces#} 3197 <p> 3198 Error Return Traces show all the points in the code that an error was returned to the calling function. This makes it practical to use {#link|try#} everywhere and then still be able to know what happened if an error ends up bubbling all the way out of your application. 3199 </p> 3200 {#code|error_return_trace.zig#} 3201 3202 <p> 3203 Look closely at this example. This is no stack trace. 3204 </p> 3205 <p> 3206 You can see that the final error bubbled up was {#syntax#}PermissionDenied{#endsyntax#}, 3207 but the original error that started this whole thing was {#syntax#}FileNotFound{#endsyntax#}. In the {#syntax#}bar{#endsyntax#} function, the code handles the original error code, 3208 and then returns another one, from the switch statement. Error Return Traces make this clear, whereas a stack trace would look like this: 3209 </p> 3210 {#code|stack_trace.zig#} 3211 3212 <p> 3213 Here, the stack trace does not explain how the control 3214 flow in {#syntax#}bar{#endsyntax#} got to the {#syntax#}hello(){#endsyntax#} call. 3215 One would have to open a debugger or further instrument the application 3216 in order to find out. The error return trace, on the other hand, 3217 shows exactly how the error bubbled up. 3218 </p> 3219 <p> 3220 This debugging feature makes it easier to iterate quickly on code that 3221 robustly handles all error conditions. This means that Zig developers 3222 will naturally find themselves writing correct, robust code in order 3223 to increase their development pace. 3224 </p> 3225 <p> 3226 Error Return Traces are enabled by default in {#link|Debug#} builds and disabled by default in {#link|ReleaseFast#}, {#link|ReleaseSafe#} and {#link|ReleaseSmall#} builds. 3227 </p> 3228 <p> 3229 There are a few ways to activate this error return tracing feature: 3230 </p> 3231 <ul> 3232 <li>Return an error from main</li> 3233 <li>An error makes its way to {#syntax#}catch unreachable{#endsyntax#} and you have not overridden the default panic handler</li> 3234 <li>Use {#link|errorReturnTrace#} to access the current return trace. You can use {#syntax#}std.debug.dumpStackTrace{#endsyntax#} to print it. This function returns comptime-known {#link|null#} when building without error return tracing support.</li> 3235 </ul> 3236 {#header_open|Implementation Details#} 3237 <p> 3238 To analyze performance cost, there are two cases: 3239 </p> 3240 <ul> 3241 <li>when no errors are returned</li> 3242 <li>when returning errors</li> 3243 </ul> 3244 <p> 3245 For the case when no errors are returned, the cost is a single memory write operation, only in the first non-failable function in the call graph that calls a failable function, i.e. when a function returning {#syntax#}void{#endsyntax#} calls a function returning {#syntax#}error{#endsyntax#}. 3246 This is to initialize this struct in the stack memory: 3247 </p> 3248 {#syntax_block|zig|stack_trace_struct.zig#} 3249 pub const StackTrace = struct { 3250 index: usize, 3251 instruction_addresses: [N]usize, 3252 }; 3253 {#end_syntax_block#} 3254 <p> 3255 Here, N is the maximum function call depth as determined by call graph analysis. Recursion is ignored and counts for 2. 3256 </p> 3257 <p> 3258 A pointer to {#syntax#}StackTrace{#endsyntax#} is passed as a secret parameter to every function that can return an error, but it's always the first parameter, so it can likely sit in a register and stay there. 3259 </p> 3260 <p> 3261 That's it for the path when no errors occur. It's practically free in terms of performance. 3262 </p> 3263 <p> 3264 When generating the code for a function that returns an error, just before the {#syntax#}return{#endsyntax#} statement (only for the {#syntax#}return{#endsyntax#} statements that return errors), Zig generates a call to this function: 3265 </p> 3266 {#syntax_block|zig|zig_return_error_fn.zig#} 3267 // marked as "no-inline" in LLVM IR 3268 fn __zig_return_error(stack_trace: *StackTrace) void { 3269 stack_trace.instruction_addresses[stack_trace.index] = @returnAddress(); 3270 stack_trace.index = (stack_trace.index + 1) % N; 3271 } 3272 {#end_syntax_block#} 3273 <p> 3274 The cost is 2 math operations plus some memory reads and writes. The memory accessed is constrained and should remain cached for the duration of the error return bubbling. 3275 </p> 3276 <p> 3277 As for code size cost, 1 function call before a return statement is no big deal. Even so, 3278 I have <a href="https://github.com/ziglang/zig/issues/690">a plan</a> to make the call to 3279 {#syntax#}__zig_return_error{#endsyntax#} a tail call, which brings the code size cost down to actually zero. What is a return statement in code without error return tracing can become a jump instruction in code with error return tracing. 3280 </p> 3281 {#header_close#} 3282 {#header_close#} 3283 {#header_close#} 3284 {#header_open|Optionals#} 3285 <p> 3286 One area that Zig provides safety without compromising efficiency or 3287 readability is with the optional type. 3288 </p> 3289 <p> 3290 The question mark symbolizes the optional type. You can convert a type to an optional 3291 type by putting a question mark in front of it, like this: 3292 </p> 3293 {#code|optional_integer.zig#} 3294 3295 <p> 3296 Now the variable {#syntax#}optional_int{#endsyntax#} could be an {#syntax#}i32{#endsyntax#}, or {#syntax#}null{#endsyntax#}. 3297 </p> 3298 <p> 3299 Instead of integers, let's talk about pointers. Null references are the source of many runtime 3300 exceptions, and even stand accused of being 3301 <a href="https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/">the worst mistake of computer science</a>. 3302 </p> 3303 <p>Zig does not have them.</p> 3304 <p> 3305 Instead, you can use an optional pointer. This secretly compiles down to a normal pointer, 3306 since we know we can use 0 as the null value for the optional type. But the compiler 3307 can check your work and make sure you don't assign null to something that can't be null. 3308 </p> 3309 <p> 3310 Typically the downside of not having null is that it makes the code more verbose to 3311 write. But, let's compare some equivalent C code and Zig code. 3312 </p> 3313 <p> 3314 Task: call malloc, if the result is null, return null. 3315 </p> 3316 <p>C code</p> 3317 {#syntax_block|c|call_malloc_in_c.c#} 3318 // malloc prototype included for reference 3319 void *malloc(size_t size); 3320 3321 struct Foo *do_a_thing(void) { 3322 char *ptr = malloc(1234); 3323 if (!ptr) return NULL; 3324 // ... 3325 } 3326 {#end_syntax_block#} 3327 <p>Zig code</p> 3328 {#syntax_block|zig|call_malloc_from_zig.zig#} 3329 // malloc prototype included for reference 3330 extern fn malloc(size: usize) ?[*]u8; 3331 3332 fn doAThing() ?*Foo { 3333 const ptr = malloc(1234) orelse return null; 3334 _ = ptr; // ... 3335 } 3336 {#end_syntax_block#} 3337 <p> 3338 Here, Zig is at least as convenient, if not more, than C. And, the type of "ptr" 3339 is {#syntax#}[*]u8{#endsyntax#} <em>not</em> {#syntax#}?[*]u8{#endsyntax#}. The {#syntax#}orelse{#endsyntax#} keyword 3340 unwrapped the optional type and therefore {#syntax#}ptr{#endsyntax#} is guaranteed to be non-null everywhere 3341 it is used in the function. 3342 </p> 3343 <p> 3344 The other form of checking against NULL you might see looks like this: 3345 </p> 3346 {#syntax_block|c|checking_null_in_c.c#} 3347 void do_a_thing(struct Foo *foo) { 3348 // do some stuff 3349 3350 if (foo) { 3351 do_something_with_foo(foo); 3352 } 3353 3354 // do some stuff 3355 } 3356 {#end_syntax_block#} 3357 <p> 3358 In Zig you can accomplish the same thing: 3359 </p> 3360 {#code|checking_null_in_zig.zig#} 3361 3362 <p> 3363 Once again, the notable thing here is that inside the if block, 3364 {#syntax#}foo{#endsyntax#} is no longer an optional pointer, it is a pointer, which 3365 cannot be null. 3366 </p> 3367 <p> 3368 One benefit to this is that functions which take pointers as arguments can 3369 be annotated with the "nonnull" attribute - <code>__attribute__((nonnull))</code> in 3370 <a href="https://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Function-Attributes.html">GCC</a>. 3371 The optimizer can sometimes make better decisions knowing that pointer arguments 3372 cannot be null. 3373 </p> 3374 {#header_open|Optional Type#} 3375 <p>An optional is created by putting {#syntax#}?{#endsyntax#} in front of a type. You can use compile-time 3376 reflection to access the child type of an optional:</p> 3377 {#code|test_optional_type.zig#} 3378 3379 {#header_close#} 3380 {#header_open|null#} 3381 <p> 3382 Just like {#link|undefined#}, {#syntax#}null{#endsyntax#} has its own type, and the only way to use it is to 3383 cast it to a different type: 3384 </p> 3385 {#code|null.zig#} 3386 3387 {#header_close#} 3388 {#header_open|Optional Pointers#} 3389 <p>An optional pointer is guaranteed to be the same size as a pointer. The {#syntax#}null{#endsyntax#} of 3390 the optional is guaranteed to be address 0.</p> 3391 {#code|test_optional_pointer.zig#} 3392 3393 {#header_close#} 3394 3395 {#see_also|while with Optionals|if with Optionals#} 3396 {#header_close#} 3397 {#header_open|Casting#} 3398 <p> 3399 A <strong>type cast</strong> converts a value of one type to another. 3400 Zig has {#link|Type Coercion#} for conversions that are known to be completely safe and unambiguous, 3401 and {#link|Explicit Casts#} for conversions that one would not want to happen on accident. 3402 There is also a third kind of type conversion called {#link|Peer Type Resolution#} for 3403 the case when a result type must be decided given multiple operand types. 3404 </p> 3405 {#header_open|Type Coercion#} 3406 <p> 3407 Type coercion occurs when one type is expected, but different type is provided: 3408 </p> 3409 {#code|test_type_coercion.zig#} 3410 3411 <p> 3412 Type coercions are only allowed when it is completely unambiguous how to get from one type to another, 3413 and the transformation is guaranteed to be safe. There is one exception, which is {#link|C Pointers#}. 3414 </p> 3415 {#header_open|Type Coercion: Stricter Qualification#} 3416 <p> 3417 Values which have the same representation at runtime can be cast to increase the strictness 3418 of the qualifiers, no matter how nested the qualifiers are: 3419 </p> 3420 <ul> 3421 <li>{#syntax#}const{#endsyntax#} - non-const to const is allowed</li> 3422 <li>{#syntax#}volatile{#endsyntax#} - non-volatile to volatile is allowed</li> 3423 <li>{#syntax#}align{#endsyntax#} - bigger to smaller alignment is allowed </li> 3424 <li>{#link|error sets|Error Set Type#} to supersets is allowed</li> 3425 </ul> 3426 <p> 3427 These casts are no-ops at runtime since the value representation does not change. 3428 </p> 3429 {#code|test_no_op_casts.zig#} 3430 3431 <p> 3432 In addition, pointers coerce to const optional pointers: 3433 </p> 3434 {#code|test_pointer_coerce_const_optional.zig#} 3435 3436 {#header_close#} 3437 {#header_open|Type Coercion: Integer and Float Widening#} 3438 <p> 3439 {#link|Integers#} coerce to integer types which can represent every value of the old type, and likewise 3440 {#link|Floats#} coerce to float types which can represent every value of the old type. 3441 </p> 3442 {#code|test_integer_widening.zig#} 3443 3444 {#header_close#} 3445 {#header_open|Type Coercion: Float to Int#} 3446 <p> 3447 A compiler error is appropriate because this ambiguous expression leaves the compiler 3448 two choices about the coercion. 3449 </p> 3450 <ul> 3451 <li>Cast {#syntax#}54.0{#endsyntax#} to {#syntax#}comptime_int{#endsyntax#} resulting in {#syntax#}@as(comptime_int, 10){#endsyntax#}, which is casted to {#syntax#}@as(f32, 10){#endsyntax#}</li> 3452 <li>Cast {#syntax#}5{#endsyntax#} to {#syntax#}comptime_float{#endsyntax#} resulting in {#syntax#}@as(comptime_float, 10.8){#endsyntax#}, which is casted to {#syntax#}@as(f32, 10.8){#endsyntax#}</li> 3453 </ul> 3454 {#code|test_ambiguous_coercion.zig#} 3455 3456 {#header_close#} 3457 {#header_open|Type Coercion: Slices, Arrays and Pointers#} 3458 {#code|test_coerce_slices_arrays_and_pointers.zig#} 3459 3460 {#see_also|C Pointers#} 3461 {#header_close#} 3462 {#header_open|Type Coercion: Optionals#} 3463 <p> 3464 The payload type of {#link|Optionals#}, as well as {#link|null#}, coerce to the optional type. 3465 </p> 3466 {#code|test_coerce_optionals.zig#} 3467 3468 <p>Optionals work nested inside the {#link|Error Union Type#}, too:</p> 3469 {#code|test_coerce_optional_wrapped_error_union.zig#} 3470 3471 {#header_close#} 3472 {#header_open|Type Coercion: Error Unions#} 3473 <p>The payload type of an {#link|Error Union Type#} as well as the {#link|Error Set Type#} 3474 coerce to the error union type: 3475 </p> 3476 {#code|test_coerce_to_error_union.zig#} 3477 3478 {#header_close#} 3479 {#header_open|Type Coercion: Compile-Time Known Numbers#} 3480 <p>When a number is {#link|comptime#}-known to be representable in the destination type, 3481 it may be coerced: 3482 </p> 3483 {#code|test_coerce_large_to_small.zig#} 3484 3485 {#header_close#} 3486 {#header_open|Type Coercion: Unions and Enums#} 3487 <p>Tagged unions can be coerced to enums, and enums can be coerced to tagged unions 3488 when they are {#link|comptime#}-known to be a field of the union that has only one possible value, such as 3489 {#link|void#}: 3490 </p> 3491 {#code|test_coerce_unions_enums.zig#} 3492 3493 {#see_also|union|enum#} 3494 {#header_close#} 3495 {#header_open|Type Coercion: undefined#} 3496 <p>{#link|undefined#} can be coerced to any type.</p> 3497 {#header_close#} 3498 3499 {#header_open|Type Coercion: Tuples to Arrays#} 3500 <p>{#link|Tuples#} can be coerced to arrays, if all of the fields have the same type.</p> 3501 {#code|test_coerce_tuples_arrays.zig#} 3502 3503 {#header_close#} 3504 {#header_close#} 3505 3506 {#header_open|Explicit Casts#} 3507 <p> 3508 Explicit casts are performed via {#link|Builtin Functions#}. 3509 Some explicit casts are safe; some are not. 3510 Some explicit casts perform language-level assertions; some do not. 3511 Some explicit casts are no-ops at runtime; some are not. 3512 </p> 3513 <ul> 3514 <li>{#link|@bitCast#} - change type but maintain bit representation</li> 3515 <li>{#link|@alignCast#} - make a pointer have more alignment</li> 3516 <li>{#link|@enumFromInt#} - obtain an enum value based on its integer tag value</li> 3517 <li>{#link|@errorFromInt#} - obtain an error code based on its integer value</li> 3518 <li>{#link|@errorCast#} - convert to a smaller error set</li> 3519 <li>{#link|@floatCast#} - convert a larger float to a smaller float</li> 3520 <li>{#link|@floatFromInt#} - convert an integer to a float value</li> 3521 <li>{#link|@intCast#} - convert between integer types</li> 3522 <li>{#link|@intFromBool#} - convert true to 1 and false to 0</li> 3523 <li>{#link|@intFromEnum#} - obtain the integer tag value of an enum or tagged union</li> 3524 <li>{#link|@intFromError#} - obtain the integer value of an error code</li> 3525 <li>{#link|@intFromFloat#} - obtain the integer part of a float value</li> 3526 <li>{#link|@intFromPtr#} - obtain the address of a pointer</li> 3527 <li>{#link|@ptrFromInt#} - convert an address to a pointer</li> 3528 <li>{#link|@ptrCast#} - convert between pointer types</li> 3529 <li>{#link|@truncate#} - convert between integer types, chopping off bits</li> 3530 </ul> 3531 {#header_close#} 3532 3533 {#header_open|Peer Type Resolution#} 3534 <p>Peer Type Resolution occurs in these places:</p> 3535 <ul> 3536 <li>{#link|switch#} expressions</li> 3537 <li>{#link|if#} expressions</li> 3538 <li>{#link|while#} expressions</li> 3539 <li>{#link|for#} expressions</li> 3540 <li>Multiple break statements in a block</li> 3541 <li>Some {#link|binary operations|Table of Operators#}</li> 3542 </ul> 3543 <p> 3544 This kind of type resolution chooses a type that all peer types can coerce into. Here are 3545 some examples: 3546 </p> 3547 {#code|test_peer_type_resolution.zig#} 3548 3549 {#header_close#} 3550 {#header_close#} 3551 3552 {#header_open|Zero Bit Types#} 3553 <p>For some types, {#link|@sizeOf#} is 0:</p> 3554 <ul> 3555 <li>{#link|void#}</li> 3556 <li>The {#link|Integers#} {#syntax#}u0{#endsyntax#} and {#syntax#}i0{#endsyntax#}.</li> 3557 <li>{#link|Arrays#} and {#link|Vectors#} with len 0, or with an element type that is a zero bit type.</li> 3558 <li>An {#link|enum#} with only 1 tag.</li> 3559 <li>A {#link|struct#} with all fields being zero bit types.</li> 3560 <li>A {#link|union#} with only 1 field which is a zero bit type.</li> 3561 </ul> 3562 <p> 3563 These types can only ever have one possible value, and thus 3564 require 0 bits to represent. Code that makes use of these types is 3565 not included in the final generated code: 3566 </p> 3567 {#code|zero_bit_types.zig#} 3568 3569 <p>When this turns into machine code, there is no code generated in the 3570 body of {#syntax#}entry{#endsyntax#}, even in {#link|Debug#} mode. For example, on x86_64:</p> 3571 <pre><code>0000000000000010 <entry>: 3572 10: 55 push %rbp 3573 11: 48 89 e5 mov %rsp,%rbp 3574 14: 5d pop %rbp 3575 15: c3 retq </code></pre> 3576 <p>These assembly instructions do not have any code associated with the void values - 3577 they only perform the function call prologue and epilogue.</p> 3578 3579 {#header_open|void#} 3580 <p> 3581 {#syntax#}void{#endsyntax#} can be useful for instantiating generic types. For example, given a 3582 {#syntax#}Map(Key, Value){#endsyntax#}, one can pass {#syntax#}void{#endsyntax#} for the {#syntax#}Value{#endsyntax#} 3583 type to make it into a {#syntax#}Set{#endsyntax#}: 3584 </p> 3585 {#code|test_void_in_hashmap.zig#} 3586 3587 <p>Note that this is different from using a dummy value for the hash map value. 3588 By using {#syntax#}void{#endsyntax#} as the type of the value, the hash map entry type has no value field, and 3589 thus the hash map takes up less space. Further, all the code that deals with storing and loading the 3590 value is deleted, as seen above. 3591 </p> 3592 <p> 3593 {#syntax#}void{#endsyntax#} is distinct from {#syntax#}anyopaque{#endsyntax#}. 3594 {#syntax#}void{#endsyntax#} has a known size of 0 bytes, and {#syntax#}anyopaque{#endsyntax#} has an unknown, but non-zero, size. 3595 </p> 3596 <p> 3597 Expressions of type {#syntax#}void{#endsyntax#} are the only ones whose value can be ignored. For example, ignoring 3598 a non-{#syntax#}void{#endsyntax#} expression is a compile error: 3599 </p> 3600 {#code|test_expression_ignored.zig#} 3601 3602 <p>However, if the expression has type {#syntax#}void{#endsyntax#}, there will be no error. Expression results can be explicitly ignored by assigning them to {#syntax#}_{#endsyntax#}. </p> 3603 {#code|test_void_ignored.zig#} 3604 3605 {#header_close#} 3606 {#header_close#} 3607 3608 {#header_open|Result Location Semantics#} 3609 <p> 3610 During compilation, every Zig expression and sub-expression is assigned optional result location 3611 information. This information dictates what type the expression should have (its result type), and 3612 where the resulting value should be placed in memory (its result location). The information is 3613 optional in the sense that not every expression has this information: assignment to 3614 {#syntax#}_{#endsyntax#}, for instance, does not provide any information about the type of an 3615 expression, nor does it provide a concrete memory location to place it in. 3616 </p> 3617 <p> 3618 As a motivating example, consider the statement {#syntax#}const x: u32 = 42;{#endsyntax#}. The type 3619 annotation here provides a result type of {#syntax#}u32{#endsyntax#} to the initialization expression 3620 {#syntax#}42{#endsyntax#}, instructing the compiler to coerce this integer (initially of type 3621 {#syntax#}comptime_int{#endsyntax#}) to this type. We will see more examples shortly. 3622 </p> 3623 <p> 3624 This is not an implementation detail: the logic outlined above is codified into the Zig language 3625 specification, and is the primary mechanism of type inference in the language. This system is 3626 collectively referred to as "Result Location Semantics". 3627 </p> 3628 {#header_open|Result Types#} 3629 <p> 3630 Result types are propagated recursively through expressions where possible. For instance, if the 3631 expression {#syntax#}&e{#endsyntax#} has result type {#syntax#}*u32{#endsyntax#}, then 3632 {#syntax#}e{#endsyntax#} is given a result type of {#syntax#}u32{#endsyntax#}, allowing the 3633 language to perform this coercion before taking a reference. 3634 </p> 3635 <p> 3636 The result type mechanism is utilized by casting builtins such as {#syntax#}@intCast{#endsyntax#}. 3637 Rather than taking as an argument the type to cast to, these builtins use their result type to 3638 determine this information. The result type is often known from context; where it is not, the 3639 {#syntax#}@as{#endsyntax#} builtin can be used to explicitly provide a result type. 3640 </p> 3641 <p> 3642 We can break down the result types for each component of a simple expression as follows: 3643 </p> 3644 {#code|result_type_propagation.zig#} 3645 3646 <p> 3647 This result type information is useful for the aforementioned cast builtins, as well as to avoid 3648 the construction of pre-coercion values, and to avoid the need for explicit type coercions in some 3649 cases. The following table details how some common expressions propagate result types, where 3650 {#syntax#}x{#endsyntax#} and {#syntax#}y{#endsyntax#} are arbitrary sub-expressions. 3651 </p> 3652 <div class="table-wrapper"> 3653 <table> 3654 <thead> 3655 <tr> 3656 <th scope="col">Expression</th> 3657 <th scope="col">Parent Result Type</th> 3658 <th scope="col">Sub-expression Result Type</th> 3659 </tr> 3660 </thead> 3661 <tbody> 3662 <tr> 3663 <th scope="row">{#syntax#}const val: T = x{#endsyntax#}</th> 3664 <td>-</td> 3665 <td>{#syntax#}x{#endsyntax#} is a {#syntax#}T{#endsyntax#}</td> 3666 </tr> 3667 <tr> 3668 <th scope="row">{#syntax#}var val: T = x{#endsyntax#}</th> 3669 <td>-</td> 3670 <td>{#syntax#}x{#endsyntax#} is a {#syntax#}T{#endsyntax#}</td> 3671 </tr> 3672 <tr> 3673 <th scope="row">{#syntax#}val = x{#endsyntax#}</th> 3674 <td>-</td> 3675 <td>{#syntax#}x{#endsyntax#} is a {#syntax#}@TypeOf(val){#endsyntax#}</td> 3676 </tr> 3677 <tr> 3678 <th scope="row">{#syntax#}@as(T, x){#endsyntax#}</th> 3679 <td>-</td> 3680 <td>{#syntax#}x{#endsyntax#} is a {#syntax#}T{#endsyntax#}</td> 3681 </tr> 3682 <tr> 3683 <th scope="row">{#syntax#}&x{#endsyntax#}</th> 3684 <td>{#syntax#}*T{#endsyntax#}</td> 3685 <td>{#syntax#}x{#endsyntax#} is a {#syntax#}T{#endsyntax#}</td> 3686 </tr> 3687 <tr> 3688 <th scope="row">{#syntax#}&x{#endsyntax#}</th> 3689 <td>{#syntax#}[]T{#endsyntax#}</td> 3690 <td>{#syntax#}x{#endsyntax#} is some array of {#syntax#}T{#endsyntax#}</td> 3691 </tr> 3692 <tr> 3693 <th scope="row">{#syntax#}f(x){#endsyntax#}</th> 3694 <td>-</td> 3695 <td>{#syntax#}x{#endsyntax#} has the type of the first parameter of {#syntax#}f{#endsyntax#}</td> 3696 </tr> 3697 <tr> 3698 <th scope="row">{#syntax#}.{x}{#endsyntax#}</th> 3699 <td>{#syntax#}T{#endsyntax#}</td> 3700 <td>{#syntax#}x{#endsyntax#} is a {#syntax#}@FieldType(T, "0"){#endsyntax#}</td> 3701 </tr> 3702 <tr> 3703 <th scope="row">{#syntax#}.{ .a = x }{#endsyntax#}</th> 3704 <td>{#syntax#}T{#endsyntax#}</td> 3705 <td>{#syntax#}x{#endsyntax#} is a {#syntax#}@FieldType(T, "a"){#endsyntax#}</td> 3706 </tr> 3707 <tr> 3708 <th scope="row">{#syntax#}T{x}{#endsyntax#}</th> 3709 <td>-</td> 3710 <td>{#syntax#}x{#endsyntax#} is a {#syntax#}@FieldType(T, "0"){#endsyntax#}</td> 3711 </tr> 3712 <tr> 3713 <th scope="row">{#syntax#}T{ .a = x }{#endsyntax#}</th> 3714 <td>-</td> 3715 <td>{#syntax#}x{#endsyntax#} is a {#syntax#}@FieldType(T, "a"){#endsyntax#}</td> 3716 </tr> 3717 <tr> 3718 <th scope="row">{#syntax#}@Type(x){#endsyntax#}</th> 3719 <td>-</td> 3720 <td>{#syntax#}x{#endsyntax#} is a {#syntax#}std.builtin.Type{#endsyntax#}</td> 3721 </tr> 3722 <tr> 3723 <th scope="row">{#syntax#}@typeInfo(x){#endsyntax#}</th> 3724 <td>-</td> 3725 <td>{#syntax#}x{#endsyntax#} is a {#syntax#}type{#endsyntax#}</td> 3726 </tr> 3727 <tr> 3728 <th scope="row">{#syntax#}x << y{#endsyntax#}</th> 3729 <td>-</td> 3730 <td>{#syntax#}y{#endsyntax#} is a {#syntax#}std.math.Log2IntCeil(@TypeOf(x)){#endsyntax#}</td> 3731 </tr> 3732 </tbody> 3733 </table> 3734 </div> 3735 {#header_close#} 3736 {#header_open|Result Locations#} 3737 <p> 3738 In addition to result type information, every expression may be optionally assigned a result 3739 location: a pointer to which the value must be directly written. This system can be used to prevent 3740 intermediate copies when initializing data structures, which can be important for types which must 3741 have a fixed memory address ("pinned" types). 3742 </p> 3743 <p> 3744 When compiling the simple assignment expression {#syntax#}x = e{#endsyntax#}, many languages would 3745 create the temporary value {#syntax#}e{#endsyntax#} on the stack, and then assign it to 3746 {#syntax#}x{#endsyntax#}, potentially performing a type coercion in the process. Zig approaches this 3747 differently. The expression {#syntax#}e{#endsyntax#} is given a result type matching the type of 3748 {#syntax#}x{#endsyntax#}, and a result location of {#syntax#}&x{#endsyntax#}. For many syntactic 3749 forms of {#syntax#}e{#endsyntax#}, this has no practical impact. However, it can have important 3750 semantic effects when working with more complex syntax forms. 3751 </p> 3752 <p> 3753 For instance, if the expression {#syntax#}.{ .a = x, .b = y }{#endsyntax#} has a result location of 3754 {#syntax#}ptr{#endsyntax#}, then {#syntax#}x{#endsyntax#} is given a result location of 3755 {#syntax#}&ptr.a{#endsyntax#}, and {#syntax#}y{#endsyntax#} a result location of {#syntax#}&ptr.b{#endsyntax#}. 3756 Without this system, this expression would construct a temporary struct value entirely on the stack, and 3757 only then copy it to the destination address. In essence, Zig desugars the assignment 3758 {#syntax#}foo = .{ .a = x, .b = y }{#endsyntax#} to the two statements {#syntax#}foo.a = x; foo.b = y;{#endsyntax#}. 3759 </p> 3760 <p> 3761 This can sometimes be important when assigning an aggregate value where the initialization 3762 expression depends on the previous value of the aggregate. The easiest way to demonstrate this is by 3763 attempting to swap fields of a struct or array - the following logic looks sound, but in fact is not: 3764 </p> 3765 {#code|result_location_interfering_with_swap.zig#} 3766 3767 <p> 3768 The following table details how some common expressions propagate result locations, where 3769 {#syntax#}x{#endsyntax#} and {#syntax#}y{#endsyntax#} are arbitrary sub-expressions. Note that 3770 some expressions cannot provide meaningful result locations to sub-expressions, even if they 3771 themselves have a result location. 3772 </p> 3773 <div class="table-wrapper"> 3774 <table> 3775 <thead> 3776 <tr> 3777 <th scope="col">Expression</th> 3778 <th scope="col">Result Location</th> 3779 <th scope="col">Sub-expression Result Locations</th> 3780 </tr> 3781 </thead> 3782 <tbody> 3783 <tr> 3784 <th scope="row">{#syntax#}const val: T = x{#endsyntax#}</th> 3785 <td>-</td> 3786 <td>{#syntax#}x{#endsyntax#} has result location {#syntax#}&val{#endsyntax#}</td> 3787 </tr> 3788 <tr> 3789 <th scope="row">{#syntax#}var val: T = x{#endsyntax#}</th> 3790 <td>-</td> 3791 <td>{#syntax#}x{#endsyntax#} has result location {#syntax#}&val{#endsyntax#}</td> 3792 </tr> 3793 <tr> 3794 <th scope="row">{#syntax#}val = x{#endsyntax#}</th> 3795 <td>-</td> 3796 <td>{#syntax#}x{#endsyntax#} has result location {#syntax#}&val{#endsyntax#}</td> 3797 </tr> 3798 <tr> 3799 <th scope="row">{#syntax#}@as(T, x){#endsyntax#}</th> 3800 <td>{#syntax#}ptr{#endsyntax#}</td> 3801 <td>{#syntax#}x{#endsyntax#} has no result location</td> 3802 </tr> 3803 <tr> 3804 <th scope="row">{#syntax#}&x{#endsyntax#}</th> 3805 <td>{#syntax#}ptr{#endsyntax#}</td> 3806 <td>{#syntax#}x{#endsyntax#} has no result location</td> 3807 </tr> 3808 <tr> 3809 <th scope="row">{#syntax#}f(x){#endsyntax#}</th> 3810 <td>{#syntax#}ptr{#endsyntax#}</td> 3811 <td>{#syntax#}x{#endsyntax#} has no result location</td> 3812 </tr> 3813 <tr> 3814 <th scope="row">{#syntax#}.{x}{#endsyntax#}</th> 3815 <td>{#syntax#}ptr{#endsyntax#}</td> 3816 <td>{#syntax#}x{#endsyntax#} has result location {#syntax#}&ptr[0]{#endsyntax#}</td> 3817 </tr> 3818 <tr> 3819 <th scope="row">{#syntax#}.{ .a = x }{#endsyntax#}</th> 3820 <td>{#syntax#}ptr{#endsyntax#}</td> 3821 <td>{#syntax#}x{#endsyntax#} has result location {#syntax#}&ptr.a{#endsyntax#}</td> 3822 </tr> 3823 <tr> 3824 <th scope="row">{#syntax#}T{x}{#endsyntax#}</th> 3825 <td>{#syntax#}ptr{#endsyntax#}</td> 3826 <td>{#syntax#}x{#endsyntax#} has no result location (typed initializers do not propagate result locations)</td> 3827 </tr> 3828 <tr> 3829 <th scope="row">{#syntax#}T{ .a = x }{#endsyntax#}</th> 3830 <td>{#syntax#}ptr{#endsyntax#}</td> 3831 <td>{#syntax#}x{#endsyntax#} has no result location (typed initializers do not propagate result locations)</td> 3832 </tr> 3833 <tr> 3834 <th scope="row">{#syntax#}@Type(x){#endsyntax#}</th> 3835 <td>{#syntax#}ptr{#endsyntax#}</td> 3836 <td>{#syntax#}x{#endsyntax#} has no result location</td> 3837 </tr> 3838 <tr> 3839 <th scope="row">{#syntax#}@typeInfo(x){#endsyntax#}</th> 3840 <td>{#syntax#}ptr{#endsyntax#}</td> 3841 <td>{#syntax#}x{#endsyntax#} has no result location</td> 3842 </tr> 3843 <tr> 3844 <th scope="row">{#syntax#}x << y{#endsyntax#}</th> 3845 <td>{#syntax#}ptr{#endsyntax#}</td> 3846 <td>{#syntax#}x{#endsyntax#} and {#syntax#}y{#endsyntax#} do not have result locations</td> 3847 </tr> 3848 </tbody> 3849 </table> 3850 </div> 3851 {#header_close#} 3852 {#header_close#} 3853 3854 {#header_open|comptime#} 3855 <p> 3856 Zig places importance on the concept of whether an expression is known at compile-time. 3857 There are a few different places this concept is used, and these building blocks are used 3858 to keep the language small, readable, and powerful. 3859 </p> 3860 {#header_open|Introducing the Compile-Time Concept#} 3861 {#header_open|Compile-Time Parameters#} 3862 <p> 3863 Compile-time parameters is how Zig implements generics. It is compile-time duck typing. 3864 </p> 3865 {#code|compile-time_duck_typing.zig#} 3866 3867 <p> 3868 In Zig, types are first-class citizens. They can be assigned to variables, passed as parameters to functions, 3869 and returned from functions. However, they can only be used in expressions which are known at <em>compile-time</em>, 3870 which is why the parameter {#syntax#}T{#endsyntax#} in the above snippet must be marked with {#syntax#}comptime{#endsyntax#}. 3871 </p> 3872 <p> 3873 A {#syntax#}comptime{#endsyntax#} parameter means that: 3874 </p> 3875 <ul> 3876 <li>At the callsite, the value must be known at compile-time, or it is a compile error.</li> 3877 <li>In the function definition, the value is known at compile-time.</li> 3878 </ul> 3879 <p> 3880 For example, if we were to introduce another function to the above snippet: 3881 </p> 3882 {#code|test_unresolved_comptime_value.zig#} 3883 3884 <p> 3885 This is an error because the programmer attempted to pass a value only known at run-time 3886 to a function which expects a value known at compile-time. 3887 </p> 3888 <p> 3889 Another way to get an error is if we pass a type that violates the type checker when the 3890 function is analyzed. This is what it means to have <em>compile-time duck typing</em>. 3891 </p> 3892 <p> 3893 For example: 3894 </p> 3895 {#code|test_comptime_mismatched_type.zig#} 3896 3897 <p> 3898 On the flip side, inside the function definition with the {#syntax#}comptime{#endsyntax#} parameter, the 3899 value is known at compile-time. This means that we actually could make this work for the bool type 3900 if we wanted to: 3901 </p> 3902 {#code|test_comptime_max_with_bool.zig#} 3903 3904 <p> 3905 This works because Zig implicitly inlines {#syntax#}if{#endsyntax#} expressions when the condition 3906 is known at compile-time, and the compiler guarantees that it will skip analysis of 3907 the branch not taken. 3908 </p> 3909 <p> 3910 This means that the actual function generated for {#syntax#}max{#endsyntax#} in this situation looks like 3911 this: 3912 </p> 3913 {#code|compiler_generated_function.zig#} 3914 3915 <p> 3916 All the code that dealt with compile-time known values is eliminated and we are left with only 3917 the necessary run-time code to accomplish the task. 3918 </p> 3919 <p> 3920 This works the same way for {#syntax#}switch{#endsyntax#} expressions - they are implicitly inlined 3921 when the target expression is compile-time known. 3922 </p> 3923 {#header_close#} 3924 {#header_open|Compile-Time Variables#} 3925 <p> 3926 In Zig, the programmer can label variables as {#syntax#}comptime{#endsyntax#}. This guarantees to the compiler 3927 that every load and store of the variable is performed at compile-time. Any violation of this results in a 3928 compile error. 3929 </p> 3930 <p> 3931 This combined with the fact that we can {#syntax#}inline{#endsyntax#} loops allows us to write 3932 a function which is partially evaluated at compile-time and partially at run-time. 3933 </p> 3934 <p> 3935 For example: 3936 </p> 3937 {#code|test_comptime_evaluation.zig#} 3938 3939 <p> 3940 This example is a bit contrived, because the compile-time evaluation component is unnecessary; 3941 this code would work fine if it was all done at run-time. But it does end up generating 3942 different code. In this example, the function {#syntax#}performFn{#endsyntax#} is generated three different times, 3943 for the different values of {#syntax#}prefix_char{#endsyntax#} provided: 3944 </p> 3945 {#syntax_block|zig|performFn_1#} 3946 // From the line: 3947 // expect(performFn('t', 1) == 6); 3948 fn performFn(start_value: i32) i32 { 3949 var result: i32 = start_value; 3950 result = two(result); 3951 result = three(result); 3952 return result; 3953 } 3954 {#end_syntax_block#} 3955 {#syntax_block|zig|performFn_2#} 3956 // From the line: 3957 // expect(performFn('o', 0) == 1); 3958 fn performFn(start_value: i32) i32 { 3959 var result: i32 = start_value; 3960 result = one(result); 3961 return result; 3962 } 3963 {#end_syntax_block#} 3964 {#syntax_block|zig|performFn_3#} 3965 // From the line: 3966 // expect(performFn('w', 99) == 99); 3967 fn performFn(start_value: i32) i32 { 3968 var result: i32 = start_value; 3969 _ = &result; 3970 return result; 3971 } 3972 {#end_syntax_block#} 3973 <p> 3974 Note that this happens even in a debug build. 3975 This is not a way to write more optimized code, but it is a way to make sure that what <em>should</em> happen 3976 at compile-time, <em>does</em> happen at compile-time. This catches more errors and allows expressiveness 3977 that in other languages requires using macros, generated code, or a preprocessor to accomplish. 3978 </p> 3979 {#header_close#} 3980 {#header_open|Compile-Time Expressions#} 3981 <p> 3982 In Zig, it matters whether a given expression is known at compile-time or run-time. A programmer can 3983 use a {#syntax#}comptime{#endsyntax#} expression to guarantee that the expression will be evaluated at compile-time. 3984 If this cannot be accomplished, the compiler will emit an error. For example: 3985 </p> 3986 {#code|test_comptime_call_extern_function.zig#} 3987 3988 <p> 3989 It doesn't make sense that a program could call {#syntax#}exit(){#endsyntax#} (or any other external function) 3990 at compile-time, so this is a compile error. However, a {#syntax#}comptime{#endsyntax#} expression does much 3991 more than sometimes cause a compile error. 3992 </p> 3993 <p> 3994 Within a {#syntax#}comptime{#endsyntax#} expression: 3995 </p> 3996 <ul> 3997 <li>All variables are {#syntax#}comptime{#endsyntax#} variables.</li> 3998 <li>All {#syntax#}if{#endsyntax#}, {#syntax#}while{#endsyntax#}, {#syntax#}for{#endsyntax#}, and {#syntax#}switch{#endsyntax#} 3999 expressions are evaluated at compile-time, or emit a compile error if this is not possible.</li> 4000 <li>All {#syntax#}return{#endsyntax#} and {#syntax#}try{#endsyntax#} expressions are invalid (unless the function itself is called at compile-time).</li> 4001 <li>All code with runtime side effects or depending on runtime values emits a compile error.</li> 4002 <li>All function calls cause the compiler to interpret the function at compile-time, emitting a 4003 compile error if the function tries to do something that has global runtime side effects.</li> 4004 </ul> 4005 <p> 4006 This means that a programmer can create a function which is called both at compile-time and run-time, with 4007 no modification to the function required. 4008 </p> 4009 <p> 4010 Let's look at an example: 4011 </p> 4012 {#code|test_fibonacci_recursion.zig#} 4013 4014 <p> 4015 Imagine if we had forgotten the base case of the recursive function and tried to run the tests: 4016 </p> 4017 {#code|test_fibonacci_comptime_overflow.zig#} 4018 4019 <p> 4020 The compiler produces an error which is a stack trace from trying to evaluate the 4021 function at compile-time. 4022 </p> 4023 <p> 4024 Luckily, we used an unsigned integer, and so when we tried to subtract 1 from 0, it triggered 4025 {#link|Illegal Behavior#}, which is always a compile error if the compiler knows it happened. 4026 But what would have happened if we used a signed integer? 4027 </p> 4028 {#code|fibonacci_comptime_infinite_recursion.zig#} 4029 4030 <p> 4031 The compiler is supposed to notice that evaluating this function at 4032 compile-time took more than 1000 branches, and thus emits an error and 4033 gives up. If the programmer wants to increase the budget for compile-time 4034 computation, they can use a built-in function called 4035 {#link|@setEvalBranchQuota#} to change the default number 1000 to 4036 something else. 4037 </p> 4038 <p> 4039 However, there is a <a href="https://github.com/ziglang/zig/issues/13724">design 4040 flaw in the compiler</a> causing it to stack overflow instead of having the proper 4041 behavior here. I'm terribly sorry about that. I hope to get this resolved 4042 before the next release. 4043 </p> 4044 <p> 4045 What if we fix the base case, but put the wrong value in the 4046 {#syntax#}expect{#endsyntax#} line? 4047 </p> 4048 {#code|test_fibonacci_comptime_unreachable.zig#} 4049 4050 4051 <p> 4052 At {#link|container|Containers#} level (outside of any function), all expressions are implicitly 4053 {#syntax#}comptime{#endsyntax#} expressions. This means that we can use functions to 4054 initialize complex static data. For example: 4055 </p> 4056 {#code|test_container-level_comptime_expressions.zig#} 4057 4058 <p> 4059 When we compile this program, Zig generates the constants 4060 with the answer pre-computed. Here are the lines from the generated LLVM IR: 4061 </p> 4062 <pre><code class="llvm">@0 = internal unnamed_addr constant [25 x i32] [i32 2, i32 3, i32 5, i32 7, i32 11, i32 13, i32 17, i32 19, i32 23, i32 29, i32 31, i32 37, i32 41, i32 43, i32 47, i32 53, i32 59, i32 61, i32 67, i32 71, i32 73, i32 79, i32 83, i32 89, i32 97] 4063 @1 = internal unnamed_addr constant i32 1060</code></pre> 4064 <p> 4065 Note that we did not have to do anything special with the syntax of these functions. For example, 4066 we could call the {#syntax#}sum{#endsyntax#} function as is with a slice of numbers whose length and values were 4067 only known at run-time. 4068 </p> 4069 {#header_close#} 4070 {#header_close#} 4071 {#header_open|Generic Data Structures#} 4072 <p> 4073 Zig uses comptime capabilities to implement generic data structures without introducing any 4074 special-case syntax. 4075 </p> 4076 <p> 4077 Here is an example of a generic {#syntax#}List{#endsyntax#} data structure. 4078 </p> 4079 {#code|generic_data_structure.zig#} 4080 4081 <p> 4082 That's it. It's a function that returns an anonymous {#syntax#}struct{#endsyntax#}. 4083 For the purposes of error messages and debugging, Zig infers the name 4084 {#syntax#}"List(i32)"{#endsyntax#} from the function name and parameters invoked when creating 4085 the anonymous struct. 4086 </p> 4087 <p> 4088 To explicitly give a type a name, we assign it to a constant. 4089 </p> 4090 {#code|anonymous_struct_name.zig#} 4091 4092 <p> 4093 In this example, the {#syntax#}Node{#endsyntax#} struct refers to itself. 4094 This works because all top level declarations are order-independent. 4095 As long as the compiler can determine the size of the struct, it is free to refer to itself. 4096 In this case, {#syntax#}Node{#endsyntax#} refers to itself as a pointer, which has a 4097 well-defined size at compile time, so it works fine. 4098 </p> 4099 {#header_close#} 4100 {#header_open|Case Study: print in Zig#} 4101 <p> 4102 Putting all of this together, let's see how {#syntax#}print{#endsyntax#} works in Zig. 4103 </p> 4104 {#code|print.zig#} 4105 4106 4107 <p> 4108 Let's crack open the implementation of this and see how it works: 4109 </p> 4110 4111 {#code|poc_print_fn.zig#} 4112 4113 <p> 4114 This is a proof of concept implementation; the actual function in the standard library has more 4115 formatting capabilities. 4116 </p> 4117 <p> 4118 Note that this is not hard-coded into the Zig compiler; this is userland code in the standard library. 4119 </p> 4120 <p> 4121 When this function is analyzed from our example code above, Zig partially evaluates the function 4122 and emits a function that actually looks like this: 4123 </p> 4124 {#syntax_block|zig|Emitted print Function#} 4125 pub fn print(self: *Writer, arg0: []const u8, arg1: i32) !void { 4126 try self.write("here is a string: '"); 4127 try self.printValue(arg0); 4128 try self.write("' here is a number: "); 4129 try self.printValue(arg1); 4130 try self.write("\n"); 4131 try self.flush(); 4132 } 4133 {#end_syntax_block#} 4134 <p> 4135 {#syntax#}printValue{#endsyntax#} is a function that takes a parameter of any type, and does different things depending 4136 on the type: 4137 </p> 4138 {#code|poc_printValue_fn.zig#} 4139 4140 <p> 4141 And now, what happens if we give too many arguments to {#syntax#}print{#endsyntax#}? 4142 </p> 4143 {#code|test_print_too_many_args.zig#} 4144 4145 <p> 4146 Zig gives programmers the tools needed to protect themselves against their own mistakes. 4147 </p> 4148 <p> 4149 Zig doesn't care whether the format argument is a string literal, 4150 only that it is a compile-time known value that can be coerced to a {#syntax#}[]const u8{#endsyntax#}: 4151 </p> 4152 {#code|print_comptime-known_format.zig#} 4153 4154 <p> 4155 This works fine. 4156 </p> 4157 <p> 4158 Zig does not special case string formatting in the compiler and instead exposes enough power to accomplish this 4159 task in userland. It does so without introducing another language on top of Zig, such as 4160 a macro language or a preprocessor language. It's Zig all the way down. 4161 </p> 4162 {#header_close#} 4163 {#see_also|inline while|inline for#} 4164 {#header_close#} 4165 {#header_open|Assembly#} 4166 <p> 4167 For some use cases, it may be necessary to directly control the machine code generated 4168 by Zig programs, rather than relying on Zig's code generation. For these cases, one 4169 can use inline assembly. Here is an example of implementing Hello, World on x86_64 Linux 4170 using inline assembly: 4171 </p> 4172 {#code|inline_assembly.zig#} 4173 4174 <p> 4175 Dissecting the syntax: 4176 </p> 4177 {#code|Assembly Syntax Explained.zig#} 4178 4179 <p> 4180 For x86 and x86_64 targets, the syntax is AT&T syntax, rather than the more 4181 popular Intel syntax. This is due to technical constraints; assembly parsing is 4182 provided by LLVM and its support for Intel syntax is buggy and not well tested. 4183 </p> 4184 <p> 4185 Some day Zig may have its own assembler. This would allow it to integrate more seamlessly 4186 into the language, as well as be compatible with the popular NASM syntax. This documentation 4187 section will be updated before 1.0.0 is released, with a conclusive statement about the status 4188 of AT&T vs Intel/NASM syntax. 4189 </p> 4190 {#header_open|Output Constraints#} 4191 <p> 4192 Output constraints are still considered to be unstable in Zig, and 4193 so 4194 <a href="http://releases.llvm.org/10.0.0/docs/LangRef.html#inline-asm-constraint-string">LLVM documentation</a> 4195 and 4196 <a href="https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html">GCC documentation</a> 4197 must be used to understand the semantics. 4198 </p> 4199 <p> 4200 Note that some breaking changes to output constraints are planned with 4201 <a href="https://github.com/ziglang/zig/issues/215">issue #215</a>. 4202 </p> 4203 {#header_close#} 4204 4205 {#header_open|Input Constraints#} 4206 <p> 4207 Input constraints are still considered to be unstable in Zig, and 4208 so 4209 <a href="http://releases.llvm.org/10.0.0/docs/LangRef.html#inline-asm-constraint-string">LLVM documentation</a> 4210 and 4211 <a href="https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html">GCC documentation</a> 4212 must be used to understand the semantics. 4213 </p> 4214 <p> 4215 Note that some breaking changes to input constraints are planned with 4216 <a href="https://github.com/ziglang/zig/issues/215">issue #215</a>. 4217 </p> 4218 {#header_close#} 4219 4220 {#header_open|Clobbers#} 4221 <p> 4222 Clobbers are the set of registers whose values will not be preserved by the execution of 4223 the assembly code. These do not include output or input registers. The special clobber 4224 value of {#syntax#}"memory"{#endsyntax#} means that the assembly causes writes to 4225 arbitrary undeclared memory locations - not only the memory pointed to by a declared 4226 indirect output. 4227 </p> 4228 <p> 4229 Failure to declare the full set of clobbers for a given inline assembly 4230 expression is unchecked {#link|Illegal Behavior#}. 4231 </p> 4232 {#header_close#} 4233 4234 {#header_open|Global Assembly#} 4235 <p> 4236 When an assembly expression occurs in a {#link|container|Containers#} level {#link|comptime#} block, this is 4237 <strong>global assembly</strong>. 4238 </p> 4239 <p> 4240 This kind of assembly has different rules than inline assembly. First, {#syntax#}volatile{#endsyntax#} 4241 is not valid because all global assembly is unconditionally included. 4242 Second, there are no inputs, outputs, or clobbers. All global assembly is concatenated 4243 verbatim into one long string and assembled together. There are no template substitution rules regarding 4244 <code>%</code> as there are in inline assembly expressions. 4245 </p> 4246 {#code|test_global_assembly.zig#} 4247 4248 {#header_close#} 4249 {#header_close#} 4250 4251 {#header_open|Atomics#} 4252 <p>TODO: @atomic rmw</p> 4253 <p>TODO: builtin atomic memory ordering enum</p> 4254 4255 {#see_also|@atomicLoad|@atomicStore|@atomicRmw|@cmpxchgWeak|@cmpxchgStrong#} 4256 4257 {#header_close#} 4258 4259 {#header_open|Async Functions#} 4260 <p>Async functions regressed with the release of 0.11.0. The current plan is to 4261 reintroduce them as a lower level primitive that powers I/O implementations.</p> 4262 <p>Tracking issue: <a href="https://github.com/ziglang/zig/issues/23446">Proposal: stackless coroutines as low-level primitives</a></p> 4263 {#header_close#} 4264 4265 {#header_open|Builtin Functions|2col#} 4266 <p> 4267 Builtin functions are provided by the compiler and are prefixed with <code>@</code>. 4268 The {#syntax#}comptime{#endsyntax#} keyword on a parameter means that the parameter must be known 4269 at compile time. 4270 </p> 4271 {#header_open|@addrSpaceCast#} 4272 <pre>{#syntax#}@addrSpaceCast(ptr: anytype) anytype{#endsyntax#}</pre> 4273 <p> 4274 Converts a pointer from one address space to another. The new address space is inferred 4275 based on the result type. Depending on the current target and address spaces, this cast 4276 may be a no-op, a complex operation, or illegal. If the cast is legal, then the resulting 4277 pointer points to the same memory location as the pointer operand. It is always valid to 4278 cast a pointer between the same address spaces. 4279 </p> 4280 {#header_close#} 4281 {#header_open|@addWithOverflow#} 4282 <pre>{#syntax#}@addWithOverflow(a: anytype, b: anytype) struct { @TypeOf(a, b), u1 }{#endsyntax#}</pre> 4283 <p> 4284 Performs {#syntax#}a + b{#endsyntax#} and returns a tuple with the result and a possible overflow bit. 4285 </p> 4286 {#header_close#} 4287 {#header_open|@alignCast#} 4288 <pre>{#syntax#}@alignCast(ptr: anytype) anytype{#endsyntax#}</pre> 4289 <p> 4290 {#syntax#}ptr{#endsyntax#} can be {#syntax#}*T{#endsyntax#}, {#syntax#}?*T{#endsyntax#}, or {#syntax#}[]T{#endsyntax#}. 4291 Changes the alignment of a pointer. The alignment to use is inferred based on the result type. 4292 </p> 4293 <p>A {#link|pointer alignment safety check|Incorrect Pointer Alignment#} is added 4294 to the generated code to make sure the pointer is aligned as promised.</p> 4295 4296 {#header_close#} 4297 {#header_open|@alignOf#} 4298 <pre>{#syntax#}@alignOf(comptime T: type) comptime_int{#endsyntax#}</pre> 4299 <p> 4300 This function returns the number of bytes that this type should be aligned to 4301 for the current target to match the C ABI. When the child type of a pointer has 4302 this alignment, the alignment can be omitted from the type. 4303 </p> 4304 <pre>{#syntax#}const assert = @import("std").debug.assert; 4305 comptime { 4306 assert(*u32 == *align(@alignOf(u32)) u32); 4307 }{#endsyntax#}</pre> 4308 <p> 4309 The result is a target-specific compile time constant. It is guaranteed to be 4310 less than or equal to {#link|@sizeOf(T)|@sizeOf#}. 4311 </p> 4312 {#see_also|Alignment#} 4313 {#header_close#} 4314 4315 {#header_open|@as#} 4316 <pre>{#syntax#}@as(comptime T: type, expression) T{#endsyntax#}</pre> 4317 <p> 4318 Performs {#link|Type Coercion#}. This cast is allowed when the conversion is unambiguous and safe, 4319 and is the preferred way to convert between types, whenever possible. 4320 </p> 4321 {#header_close#} 4322 4323 {#header_open|@atomicLoad#} 4324 <pre>{#syntax#}@atomicLoad(comptime T: type, ptr: *const T, comptime ordering: AtomicOrder) T{#endsyntax#}</pre> 4325 <p> 4326 This builtin function atomically dereferences a pointer to a {#syntax#}T{#endsyntax#} and returns the value. 4327 </p> 4328 <p> 4329 {#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float, 4330 an integer, an enum, or a packed struct. 4331 </p> 4332 <p>{#syntax#}AtomicOrder{#endsyntax#} can be found with {#syntax#}@import("std").builtin.AtomicOrder{#endsyntax#}.</p> 4333 {#see_also|@atomicStore|@atomicRmw||@cmpxchgWeak|@cmpxchgStrong#} 4334 {#header_close#} 4335 4336 {#header_open|@atomicRmw#} 4337 <pre>{#syntax#}@atomicRmw(comptime T: type, ptr: *T, comptime op: AtomicRmwOp, operand: T, comptime ordering: AtomicOrder) T{#endsyntax#}</pre> 4338 <p> 4339 This builtin function dereferences a pointer to a {#syntax#}T{#endsyntax#} and atomically 4340 modifies the value and returns the previous value. 4341 </p> 4342 <p> 4343 {#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float, 4344 an integer, an enum, or a packed struct. 4345 </p> 4346 <p>{#syntax#}AtomicOrder{#endsyntax#} can be found with {#syntax#}@import("std").builtin.AtomicOrder{#endsyntax#}.</p> 4347 <p>{#syntax#}AtomicRmwOp{#endsyntax#} can be found with {#syntax#}@import("std").builtin.AtomicRmwOp{#endsyntax#}.</p> 4348 {#see_also|@atomicStore|@atomicLoad|@cmpxchgWeak|@cmpxchgStrong#} 4349 {#header_close#} 4350 4351 {#header_open|@atomicStore#} 4352 <pre>{#syntax#}@atomicStore(comptime T: type, ptr: *T, value: T, comptime ordering: AtomicOrder) void{#endsyntax#}</pre> 4353 <p> 4354 This builtin function dereferences a pointer to a {#syntax#}T{#endsyntax#} and atomically stores the given value. 4355 </p> 4356 <p> 4357 {#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float, 4358 an integer, an enum, or a packed struct. 4359 </p> 4360 <p>{#syntax#}AtomicOrder{#endsyntax#} can be found with {#syntax#}@import("std").builtin.AtomicOrder{#endsyntax#}.</p> 4361 {#see_also|@atomicLoad|@atomicRmw|@cmpxchgWeak|@cmpxchgStrong#} 4362 {#header_close#} 4363 4364 {#header_open|@bitCast#} 4365 <pre>{#syntax#}@bitCast(value: anytype) anytype{#endsyntax#}</pre> 4366 <p> 4367 Converts a value of one type to another type. The return type is the 4368 inferred result type. 4369 </p> 4370 <p> 4371 Asserts that {#syntax#}@sizeOf(@TypeOf(value)) == @sizeOf(DestType){#endsyntax#}. 4372 </p> 4373 <p> 4374 Asserts that {#syntax#}@typeInfo(DestType) != .pointer{#endsyntax#}. Use {#syntax#}@ptrCast{#endsyntax#} or {#syntax#}@ptrFromInt{#endsyntax#} if you need this. 4375 </p> 4376 <p> 4377 Can be used for these things for example: 4378 </p> 4379 <ul> 4380 <li>Convert {#syntax#}f32{#endsyntax#} to {#syntax#}u32{#endsyntax#} bits</li> 4381 <li>Convert {#syntax#}i32{#endsyntax#} to {#syntax#}u32{#endsyntax#} preserving twos complement</li> 4382 </ul> 4383 <p> 4384 Works at compile-time if {#syntax#}value{#endsyntax#} is known at compile time. It's a compile error to bitcast a value of undefined layout; this means that, besides the restriction from types which possess dedicated casting builtins (enums, pointers, error sets), bare structs, error unions, slices, optionals, and any other type without a well-defined memory layout, also cannot be used in this operation. 4385 </p> 4386 {#header_close#} 4387 4388 {#header_open|@bitOffsetOf#} 4389 <pre>{#syntax#}@bitOffsetOf(comptime T: type, comptime field_name: []const u8) comptime_int{#endsyntax#}</pre> 4390 <p> 4391 Returns the bit offset of a field relative to its containing struct. 4392 </p> 4393 <p> 4394 For non {#link|packed structs|packed struct#}, this will always be divisible by {#syntax#}8{#endsyntax#}. 4395 For packed structs, non-byte-aligned fields will share a byte offset, but they will have different 4396 bit offsets. 4397 </p> 4398 {#see_also|@offsetOf#} 4399 {#header_close#} 4400 4401 {#header_open|@bitSizeOf#} 4402 <pre>{#syntax#}@bitSizeOf(comptime T: type) comptime_int{#endsyntax#}</pre> 4403 <p> 4404 This function returns the number of bits it takes to store {#syntax#}T{#endsyntax#} in memory if the type 4405 were a field in a packed struct/union. 4406 The result is a target-specific compile time constant. 4407 </p> 4408 <p> 4409 This function measures the size at runtime. For types that are disallowed at runtime, such as 4410 {#syntax#}comptime_int{#endsyntax#} and {#syntax#}type{#endsyntax#}, the result is {#syntax#}0{#endsyntax#}. 4411 </p> 4412 {#see_also|@sizeOf|@typeInfo#} 4413 {#header_close#} 4414 4415 {#header_open|@branchHint#} 4416 <pre>{#syntax#}@branchHint(hint: BranchHint) void{#endsyntax#}</pre> 4417 <p>Hints to the optimizer how likely a given branch of control flow is to be reached.</p> 4418 <p>{#syntax#}BranchHint{#endsyntax#} can be found with {#syntax#}@import("std").builtin.BranchHint{#endsyntax#}.</p> 4419 <p>This function is only valid as the first statement in a control flow branch, or the first statement in a function.</p> 4420 {#header_close#} 4421 4422 {#header_open|@breakpoint#} 4423 <pre>{#syntax#}@breakpoint() void{#endsyntax#}</pre> 4424 <p> 4425 This function inserts a platform-specific debug trap instruction which causes 4426 debuggers to break there. 4427 Unlike for {#syntax#}@trap(){#endsyntax#}, execution may continue after this point if the program is resumed. 4428 </p> 4429 <p> 4430 This function is only valid within function scope. 4431 </p> 4432 {#see_also|@trap#} 4433 {#header_close#} 4434 4435 {#header_open|@mulAdd#} 4436 <pre>{#syntax#}@mulAdd(comptime T: type, a: T, b: T, c: T) T{#endsyntax#}</pre> 4437 <p> 4438 Fused multiply-add, similar to {#syntax#}(a * b) + c{#endsyntax#}, except 4439 only rounds once, and is thus more accurate. 4440 </p> 4441 <p> 4442 Supports {#link|Floats#} and {#link|Vectors#} of floats. 4443 </p> 4444 {#header_close#} 4445 4446 {#header_open|@byteSwap#} 4447 <pre>{#syntax#}@byteSwap(operand: anytype) T{#endsyntax#}</pre> 4448 <p>{#syntax#}@TypeOf(operand){#endsyntax#} must be an integer type or an integer vector type with bit count evenly divisible by 8.</p> 4449 <p>{#syntax#}operand{#endsyntax#} may be an {#link|integer|Integers#} or {#link|vector|Vectors#}.</p> 4450 <p> 4451 Swaps the byte order of the integer. This converts a big endian integer to a little endian integer, 4452 and converts a little endian integer to a big endian integer. 4453 </p> 4454 <p> 4455 Note that for the purposes of memory layout with respect to endianness, the integer type should be 4456 related to the number of bytes reported by {#link|@sizeOf#} bytes. This is demonstrated with 4457 {#syntax#}u24{#endsyntax#}. {#syntax#}@sizeOf(u24) == 4{#endsyntax#}, which means that a 4458 {#syntax#}u24{#endsyntax#} stored in memory takes 4 bytes, and those 4 bytes are what are swapped on 4459 a little vs big endian system. On the other hand, if {#syntax#}T{#endsyntax#} is specified to 4460 be {#syntax#}u24{#endsyntax#}, then only 3 bytes are reversed. 4461 </p> 4462 {#header_close#} 4463 4464 {#header_open|@bitReverse#} 4465 <pre>{#syntax#}@bitReverse(integer: anytype) T{#endsyntax#}</pre> 4466 <p>{#syntax#}@TypeOf(anytype){#endsyntax#} accepts any integer type or integer vector type.</p> 4467 <p> 4468 Reverses the bitpattern of an integer value, including the sign bit if applicable. 4469 </p> 4470 <p> 4471 For example 0b10110110 ({#syntax#}u8 = 182{#endsyntax#}, {#syntax#}i8 = -74{#endsyntax#}) 4472 becomes 0b01101101 ({#syntax#}u8 = 109{#endsyntax#}, {#syntax#}i8 = 109{#endsyntax#}). 4473 </p> 4474 {#header_close#} 4475 4476 {#header_open|@offsetOf#} 4477 <pre>{#syntax#}@offsetOf(comptime T: type, comptime field_name: []const u8) comptime_int{#endsyntax#}</pre> 4478 <p> 4479 Returns the byte offset of a field relative to its containing struct. 4480 </p> 4481 {#see_also|@bitOffsetOf#} 4482 {#header_close#} 4483 4484 {#header_open|@call#} 4485 <pre>{#syntax#}@call(modifier: std.builtin.CallModifier, function: anytype, args: anytype) anytype{#endsyntax#}</pre> 4486 <p> 4487 Calls a function, in the same way that invoking an expression with parentheses does: 4488 </p> 4489 {#code|test_call_builtin.zig#} 4490 4491 <p> 4492 {#syntax#}@call{#endsyntax#} allows more flexibility than normal function call syntax does. The 4493 {#syntax#}CallModifier{#endsyntax#} enum is reproduced here: 4494 </p> 4495 {#code|builtin.CallModifier struct.zig#} 4496 4497 {#header_close#} 4498 4499 {#header_open|@cDefine#} 4500 <pre>{#syntax#}@cDefine(comptime name: []const u8, value) void{#endsyntax#}</pre> 4501 <p> 4502 This function can only occur inside {#syntax#}@cImport{#endsyntax#}. 4503 </p> 4504 <p> 4505 This appends <code>#define $name $value</code> to the {#syntax#}@cImport{#endsyntax#} 4506 temporary buffer. 4507 </p> 4508 <p> 4509 To define without a value, like this: 4510 </p> 4511 <pre><code class="c">#define _GNU_SOURCE</code></pre> 4512 <p> 4513 Use the void value, like this: 4514 </p> 4515 <pre>{#syntax#}@cDefine("_GNU_SOURCE", {}){#endsyntax#}</pre> 4516 {#see_also|Import from C Header File|@cInclude|@cImport|@cUndef|void#} 4517 {#header_close#} 4518 {#header_open|@cImport#} 4519 <pre>{#syntax#}@cImport(expression) type{#endsyntax#}</pre> 4520 <p> 4521 This function parses C code and imports the functions, types, variables, 4522 and compatible macro definitions into a new empty struct type, and then 4523 returns that type. 4524 </p> 4525 <p> 4526 {#syntax#}expression{#endsyntax#} is interpreted at compile time. The builtin functions 4527 {#syntax#}@cInclude{#endsyntax#}, {#syntax#}@cDefine{#endsyntax#}, and {#syntax#}@cUndef{#endsyntax#} work 4528 within this expression, appending to a temporary buffer which is then parsed as C code. 4529 </p> 4530 <p> 4531 Usually you should only have one {#syntax#}@cImport{#endsyntax#} in your entire application, because it saves the compiler 4532 from invoking clang multiple times, and prevents inline functions from being duplicated. 4533 </p> 4534 <p> 4535 Reasons for having multiple {#syntax#}@cImport{#endsyntax#} expressions would be: 4536 </p> 4537 <ul> 4538 <li>To avoid a symbol collision, for example if foo.h and bar.h both <code>#define CONNECTION_COUNT</code></li> 4539 <li>To analyze the C code with different preprocessor defines</li> 4540 </ul> 4541 {#see_also|Import from C Header File|@cInclude|@cDefine|@cUndef#} 4542 {#header_close#} 4543 {#header_open|@cInclude#} 4544 <pre>{#syntax#}@cInclude(comptime path: []const u8) void{#endsyntax#}</pre> 4545 <p> 4546 This function can only occur inside {#syntax#}@cImport{#endsyntax#}. 4547 </p> 4548 <p> 4549 This appends <code>#include <$path>\n</code> to the {#syntax#}c_import{#endsyntax#} 4550 temporary buffer. 4551 </p> 4552 {#see_also|Import from C Header File|@cImport|@cDefine|@cUndef#} 4553 {#header_close#} 4554 4555 {#header_open|@clz#} 4556 <pre>{#syntax#}@clz(operand: anytype) anytype{#endsyntax#}</pre> 4557 <p>{#syntax#}@TypeOf(operand){#endsyntax#} must be an integer type or an integer vector type.</p> 4558 <p>{#syntax#}operand{#endsyntax#} may be an {#link|integer|Integers#} or {#link|vector|Vectors#}.</p> 4559 <p> 4560 Counts the number of most-significant (leading in a big-endian sense) zeroes in an integer - "count leading zeroes". 4561 </p> 4562 <p> 4563 The return type is an unsigned integer or vector of unsigned integers with the minimum number 4564 of bits that can represent the bit count of the integer type. 4565 </p> 4566 <p> 4567 If {#syntax#}operand{#endsyntax#} is zero, {#syntax#}@clz{#endsyntax#} returns the bit width 4568 of integer type {#syntax#}T{#endsyntax#}. 4569 </p> 4570 {#see_also|@ctz|@popCount#} 4571 {#header_close#} 4572 4573 {#header_open|@cmpxchgStrong#} 4574 <pre>{#syntax#}@cmpxchgStrong(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T{#endsyntax#}</pre> 4575 <p> 4576 This function performs a strong atomic compare-and-exchange operation, returning {#syntax#}null{#endsyntax#} 4577 if the current value is the given expected value. It's the equivalent of this code, 4578 except atomic: 4579 </p> 4580 {#code|not_atomic_cmpxchgStrong.zig#} 4581 4582 <p> 4583 If you are using cmpxchg in a retry loop, {#link|@cmpxchgWeak#} is the better choice, because it can be implemented 4584 more efficiently in machine instructions. 4585 </p> 4586 <p> 4587 {#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, 4588 an integer, an enum, or a packed struct. 4589 </p> 4590 <p>{#syntax#}@typeInfo(@TypeOf(ptr)).pointer.alignment{#endsyntax#} must be {#syntax#}>= @sizeOf(T).{#endsyntax#}</p> 4591 <p>{#syntax#}AtomicOrder{#endsyntax#} can be found with {#syntax#}@import("std").builtin.AtomicOrder{#endsyntax#}.</p> 4592 {#see_also|@atomicStore|@atomicLoad|@atomicRmw|@cmpxchgWeak#} 4593 {#header_close#} 4594 4595 {#header_open|@cmpxchgWeak#} 4596 <pre>{#syntax#}@cmpxchgWeak(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T{#endsyntax#}</pre> 4597 <p> 4598 This function performs a weak atomic compare-and-exchange operation, returning {#syntax#}null{#endsyntax#} 4599 if the current value is the given expected value. It's the equivalent of this code, 4600 except atomic: 4601 </p> 4602 {#syntax_block|zig|cmpxchgWeakButNotAtomic#} 4603 fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T { 4604 const old_value = ptr.*; 4605 if (old_value == expected_value and usuallyTrueButSometimesFalse()) { 4606 ptr.* = new_value; 4607 return null; 4608 } else { 4609 return old_value; 4610 } 4611 } 4612 {#end_syntax_block#} 4613 <p> 4614 If you are using cmpxchg in a retry loop, the sporadic failure will be no problem, and {#syntax#}cmpxchgWeak{#endsyntax#} 4615 is the better choice, because it can be implemented more efficiently in machine instructions. 4616 However if you need a stronger guarantee, use {#link|@cmpxchgStrong#}. 4617 </p> 4618 <p> 4619 {#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, 4620 an integer, an enum, or a packed struct. 4621 </p> 4622 <p>{#syntax#}@typeInfo(@TypeOf(ptr)).pointer.alignment{#endsyntax#} must be {#syntax#}>= @sizeOf(T).{#endsyntax#}</p> 4623 <p>{#syntax#}AtomicOrder{#endsyntax#} can be found with {#syntax#}@import("std").builtin.AtomicOrder{#endsyntax#}.</p> 4624 {#see_also|@atomicStore|@atomicLoad|@atomicRmw|@cmpxchgStrong#} 4625 {#header_close#} 4626 4627 {#header_open|@compileError#} 4628 <pre>{#syntax#}@compileError(comptime msg: []const u8) noreturn{#endsyntax#}</pre> 4629 <p> 4630 This function, when semantically analyzed, causes a compile error with the 4631 message {#syntax#}msg{#endsyntax#}. 4632 </p> 4633 <p> 4634 There are several ways that code avoids being semantically checked, such as 4635 using {#syntax#}if{#endsyntax#} or {#syntax#}switch{#endsyntax#} with compile time constants, 4636 and {#syntax#}comptime{#endsyntax#} functions. 4637 </p> 4638 {#header_close#} 4639 4640 {#header_open|@compileLog#} 4641 <pre>{#syntax#}@compileLog(...) void{#endsyntax#}</pre> 4642 <p> 4643 This function prints the arguments passed to it at compile-time. 4644 </p> 4645 <p> 4646 To prevent accidentally leaving compile log statements in a codebase, 4647 a compilation error is added to the build, pointing to the compile 4648 log statement. This error prevents code from being generated, but 4649 does not otherwise interfere with analysis. 4650 </p> 4651 <p> 4652 This function can be used to do "printf debugging" on 4653 compile-time executing code. 4654 </p> 4655 {#code|test_compileLog_builtin.zig#} 4656 4657 {#header_close#} 4658 4659 {#header_open|@constCast#} 4660 <pre>{#syntax#}@constCast(value: anytype) DestType{#endsyntax#}</pre> 4661 <p> 4662 Remove {#syntax#}const{#endsyntax#} qualifier from a pointer. 4663 </p> 4664 {#header_close#} 4665 4666 {#header_open|@ctz#} 4667 <pre>{#syntax#}@ctz(operand: anytype) anytype{#endsyntax#}</pre> 4668 <p>{#syntax#}@TypeOf(operand){#endsyntax#} must be an integer type or an integer vector type.</p> 4669 <p>{#syntax#}operand{#endsyntax#} may be an {#link|integer|Integers#} or {#link|vector|Vectors#}.</p> 4670 <p> 4671 Counts the number of least-significant (trailing in a big-endian sense) zeroes in an integer - "count trailing zeroes". 4672 </p> 4673 <p> 4674 The return type is an unsigned integer or vector of unsigned integers with the minimum number 4675 of bits that can represent the bit count of the integer type. 4676 </p> 4677 <p> 4678 If {#syntax#}operand{#endsyntax#} is zero, {#syntax#}@ctz{#endsyntax#} returns 4679 the bit width of integer type {#syntax#}T{#endsyntax#}. 4680 </p> 4681 {#see_also|@clz|@popCount#} 4682 {#header_close#} 4683 4684 {#header_open|@cUndef#} 4685 <pre>{#syntax#}@cUndef(comptime name: []const u8) void{#endsyntax#}</pre> 4686 <p> 4687 This function can only occur inside {#syntax#}@cImport{#endsyntax#}. 4688 </p> 4689 <p> 4690 This appends <code>#undef $name</code> to the {#syntax#}@cImport{#endsyntax#} 4691 temporary buffer. 4692 </p> 4693 {#see_also|Import from C Header File|@cImport|@cDefine|@cInclude#} 4694 {#header_close#} 4695 4696 {#header_open|@cVaArg#} 4697 <pre>{#syntax#}@cVaArg(operand: *std.builtin.VaList, comptime T: type) T{#endsyntax#}</pre> 4698 <p> 4699 Implements the C macro {#syntax#}va_arg{#endsyntax#}. 4700 </p> 4701 {#see_also|@cVaCopy|@cVaEnd|@cVaStart#} 4702 {#header_close#} 4703 {#header_open|@cVaCopy#} 4704 <pre>{#syntax#}@cVaCopy(src: *std.builtin.VaList) std.builtin.VaList{#endsyntax#}</pre> 4705 <p> 4706 Implements the C macro {#syntax#}va_copy{#endsyntax#}. 4707 </p> 4708 {#see_also|@cVaArg|@cVaEnd|@cVaStart#} 4709 {#header_close#} 4710 {#header_open|@cVaEnd#} 4711 <pre>{#syntax#}@cVaEnd(src: *std.builtin.VaList) void{#endsyntax#}</pre> 4712 <p> 4713 Implements the C macro {#syntax#}va_end{#endsyntax#}. 4714 </p> 4715 {#see_also|@cVaArg|@cVaCopy|@cVaStart#} 4716 {#header_close#} 4717 {#header_open|@cVaStart#} 4718 <pre>{#syntax#}@cVaStart() std.builtin.VaList{#endsyntax#}</pre> 4719 <p> 4720 Implements the C macro {#syntax#}va_start{#endsyntax#}. Only valid inside a variadic function. 4721 </p> 4722 {#see_also|@cVaArg|@cVaCopy|@cVaEnd#} 4723 {#header_close#} 4724 4725 {#header_open|@divExact#} 4726 <pre>{#syntax#}@divExact(numerator: T, denominator: T) T{#endsyntax#}</pre> 4727 <p> 4728 Exact division. Caller guarantees {#syntax#}denominator != 0{#endsyntax#} and 4729 {#syntax#}@divTrunc(numerator, denominator) * denominator == numerator{#endsyntax#}. 4730 </p> 4731 <ul> 4732 <li>{#syntax#}@divExact(6, 3) == 2{#endsyntax#}</li> 4733 <li>{#syntax#}@divExact(a, b) * b == a{#endsyntax#}</li> 4734 </ul> 4735 <p>For a function that returns a possible error code, use {#syntax#}@import("std").math.divExact{#endsyntax#}.</p> 4736 {#see_also|@divTrunc|@divFloor#} 4737 {#header_close#} 4738 {#header_open|@divFloor#} 4739 <pre>{#syntax#}@divFloor(numerator: T, denominator: T) T{#endsyntax#}</pre> 4740 <p> 4741 Floored division. Rounds toward negative infinity. For unsigned integers it is 4742 the same as {#syntax#}numerator / denominator{#endsyntax#}. Caller guarantees {#syntax#}denominator != 0{#endsyntax#} and 4743 {#syntax#}!(@typeInfo(T) == .int and T.is_signed and numerator == std.math.minInt(T) and denominator == -1){#endsyntax#}. 4744 </p> 4745 <ul> 4746 <li>{#syntax#}@divFloor(-5, 3) == -2{#endsyntax#}</li> 4747 <li>{#syntax#}(@divFloor(a, b) * b) + @mod(a, b) == a{#endsyntax#}</li> 4748 </ul> 4749 <p>For a function that returns a possible error code, use {#syntax#}@import("std").math.divFloor{#endsyntax#}.</p> 4750 {#see_also|@divTrunc|@divExact#} 4751 {#header_close#} 4752 {#header_open|@divTrunc#} 4753 <pre>{#syntax#}@divTrunc(numerator: T, denominator: T) T{#endsyntax#}</pre> 4754 <p> 4755 Truncated division. Rounds toward zero. For unsigned integers it is 4756 the same as {#syntax#}numerator / denominator{#endsyntax#}. Caller guarantees {#syntax#}denominator != 0{#endsyntax#} and 4757 {#syntax#}!(@typeInfo(T) == .int and T.is_signed and numerator == std.math.minInt(T) and denominator == -1){#endsyntax#}. 4758 </p> 4759 <ul> 4760 <li>{#syntax#}@divTrunc(-5, 3) == -1{#endsyntax#}</li> 4761 <li>{#syntax#}(@divTrunc(a, b) * b) + @rem(a, b) == a{#endsyntax#}</li> 4762 </ul> 4763 <p>For a function that returns a possible error code, use {#syntax#}@import("std").math.divTrunc{#endsyntax#}.</p> 4764 {#see_also|@divFloor|@divExact#} 4765 {#header_close#} 4766 4767 {#header_open|@embedFile#} 4768 <pre>{#syntax#}@embedFile(comptime path: []const u8) *const [N:0]u8{#endsyntax#}</pre> 4769 <p> 4770 This function returns a compile time constant pointer to null-terminated, 4771 fixed-size array with length equal to the byte count of the file given by 4772 {#syntax#}path{#endsyntax#}. The contents of the array are the contents of the file. 4773 This is equivalent to a {#link|string literal|String Literals and Unicode Code Point Literals#} 4774 with the file contents. 4775 </p> 4776 <p> 4777 {#syntax#}path{#endsyntax#} is absolute or relative to the current file, just like {#syntax#}@import{#endsyntax#}. 4778 </p> 4779 {#see_also|@import#} 4780 {#header_close#} 4781 4782 {#header_open|@enumFromInt#} 4783 <pre>{#syntax#}@enumFromInt(integer: anytype) anytype{#endsyntax#}</pre> 4784 <p> 4785 Converts an integer into an {#link|enum#} value. The return type is the inferred result type. 4786 </p> 4787 <p> 4788 Attempting to convert an integer with no corresponding value in the enum invokes 4789 safety-checked {#link|Illegal Behavior#}. 4790 Note that a {#link|non-exhaustive enum|Non-exhaustive enum#} has corresponding values for all 4791 integers in the enum's integer tag type: the {#syntax#}_{#endsyntax#} value represents all 4792 the remaining unnamed integers in the enum's tag type. 4793 </p> 4794 {#see_also|@intFromEnum#} 4795 {#header_close#} 4796 4797 {#header_open|@errorFromInt#} 4798 <pre>{#syntax#}@errorFromInt(value: std.meta.Int(.unsigned, @bitSizeOf(anyerror))) anyerror{#endsyntax#}</pre> 4799 <p> 4800 Converts from the integer representation of an error into {#link|The Global Error Set#} type. 4801 </p> 4802 <p> 4803 It is generally recommended to avoid this 4804 cast, as the integer representation of an error is not stable across source code changes. 4805 </p> 4806 <p> 4807 Attempting to convert an integer that does not correspond to any error results in 4808 safety-checked {#link|Illegal Behavior#}. 4809 </p> 4810 {#see_also|@intFromError#} 4811 {#header_close#} 4812 4813 {#header_open|@errorName#} 4814 <pre>{#syntax#}@errorName(err: anyerror) [:0]const u8{#endsyntax#}</pre> 4815 <p> 4816 This function returns the string representation of an error. The string representation 4817 of {#syntax#}error.OutOfMem{#endsyntax#} is {#syntax#}"OutOfMem"{#endsyntax#}. 4818 </p> 4819 <p> 4820 If there are no calls to {#syntax#}@errorName{#endsyntax#} in an entire application, 4821 or all calls have a compile-time known value for {#syntax#}err{#endsyntax#}, then no 4822 error name table will be generated. 4823 </p> 4824 {#header_close#} 4825 4826 {#header_open|@errorReturnTrace#} 4827 <pre>{#syntax#}@errorReturnTrace() ?*builtin.StackTrace{#endsyntax#}</pre> 4828 <p> 4829 If the binary is built with error return tracing, and this function is invoked in a 4830 function that calls a function with an error or error union return type, returns a 4831 stack trace object. Otherwise returns {#link|null#}. 4832 </p> 4833 {#header_close#} 4834 4835 {#header_open|@errorCast#} 4836 <pre>{#syntax#}@errorCast(value: anytype) anytype{#endsyntax#}</pre> 4837 <p> 4838 Converts an error set or error union value from one error set to another error set. The return type is the 4839 inferred result type. Attempting to convert an error which is not in the destination error 4840 set results in safety-checked {#link|Illegal Behavior#}. 4841 </p> 4842 {#header_close#} 4843 4844 {#header_open|@export#} 4845 <pre>{#syntax#}@export(comptime ptr: *const anyopaque, comptime options: std.builtin.ExportOptions) void{#endsyntax#}</pre> 4846 <p>Creates a symbol in the output object file which refers to the target of <code>ptr</code>.</p> 4847 <p><code>ptr</code> must point to a global variable or a comptime-known constant.</p> 4848 <p> 4849 This builtin can be called from a {#link|comptime#} block to conditionally export symbols. 4850 When <code>ptr</code> points to a function with the C calling convention and 4851 {#syntax#}options.linkage{#endsyntax#} is {#syntax#}.strong{#endsyntax#}, this is equivalent to 4852 the {#syntax#}export{#endsyntax#} keyword used on a function: 4853 </p> 4854 {#code|export_builtin.zig#} 4855 4856 <p>This is equivalent to:</p> 4857 {#code|export_builtin_equivalent_code.zig#} 4858 4859 <p>Note that even when using {#syntax#}export{#endsyntax#}, the {#syntax#}@"foo"{#endsyntax#} syntax for 4860 {#link|identifiers|Identifiers#} can be used to choose any string for the symbol name:</p> 4861 {#code|export_any_symbol_name.zig#} 4862 4863 <p> 4864 When looking at the resulting object, you can see the symbol is used verbatim: 4865 </p> 4866 <pre><code>00000000000001f0 T A function name that is a complete sentence.</code></pre> 4867 {#see_also|Exporting a C Library#} 4868 {#header_close#} 4869 4870 {#header_open|@extern#} 4871 <pre>{#syntax#}@extern(T: type, comptime options: std.builtin.ExternOptions) T{#endsyntax#}</pre> 4872 <p> 4873 Creates a reference to an external symbol in the output object file. 4874 T must be a pointer type. 4875 </p> 4876 {#see_also|@export#} 4877 {#header_close#} 4878 4879 {#header_open|@field#} 4880 <pre>{#syntax#}@field(lhs: anytype, comptime field_name: []const u8) (field){#endsyntax#}</pre> 4881 <p>Performs field access by a compile-time string. Works on both fields and declarations. 4882 </p> 4883 {#code|test_field_builtin.zig#} 4884 4885 4886 {#header_close#} 4887 4888 {#header_open|@fieldParentPtr#} 4889 <pre>{#syntax#}@fieldParentPtr(comptime field_name: []const u8, field_ptr: *T) anytype{#endsyntax#}</pre> 4890 <p> 4891 Given a pointer to a struct or union field, returns a pointer to the struct or union containing that field. 4892 The return type (pointer to the parent struct or union in question) is the inferred result type. 4893 </p> 4894 <p> 4895 If {#syntax#}field_ptr{#endsyntax#} does not point to the {#syntax#}field_name{#endsyntax#} field of an instance of 4896 the result type, and the result type has ill-defined layout, invokes unchecked {#link|Illegal Behavior#}. 4897 </p> 4898 {#header_close#} 4899 4900 {#header_open|@FieldType#} 4901 <pre>{#syntax#}@FieldType(comptime Type: type, comptime field_name: []const u8) type{#endsyntax#}</pre> 4902 <p> 4903 Given a type and the name of one of its fields, returns the type of that field. 4904 </p> 4905 {#header_close#} 4906 4907 {#header_open|@floatCast#} 4908 <pre>{#syntax#}@floatCast(value: anytype) anytype{#endsyntax#}</pre> 4909 <p> 4910 Convert from one float type to another. This cast is safe, but may cause the 4911 numeric value to lose precision. The return type is the inferred result type. 4912 </p> 4913 {#header_close#} 4914 4915 {#header_open|@floatFromInt#} 4916 <pre>{#syntax#}@floatFromInt(int: anytype) anytype{#endsyntax#}</pre> 4917 <p> 4918 Converts an integer to the closest floating point representation. The return type is the inferred result type. 4919 To convert the other way, use {#link|@intFromFloat#}. This operation is legal 4920 for all values of all integer types. 4921 </p> 4922 {#header_close#} 4923 4924 {#header_open|@frameAddress#} 4925 <pre>{#syntax#}@frameAddress() usize{#endsyntax#}</pre> 4926 <p> 4927 This function returns the base pointer of the current stack frame. 4928 </p> 4929 <p> 4930 The implications of this are target-specific and not consistent across all 4931 platforms. The frame address may not be available in release mode due to 4932 aggressive optimizations. 4933 </p> 4934 <p> 4935 This function is only valid within function scope. 4936 </p> 4937 {#header_close#} 4938 4939 {#header_open|@hasDecl#} 4940 <pre>{#syntax#}@hasDecl(comptime Container: type, comptime name: []const u8) bool{#endsyntax#}</pre> 4941 <p> 4942 Returns whether or not a {#link|container|Containers#} has a declaration 4943 matching {#syntax#}name{#endsyntax#}. 4944 </p> 4945 {#code|test_hasDecl_builtin.zig#} 4946 4947 {#see_also|@hasField#} 4948 {#header_close#} 4949 4950 {#header_open|@hasField#} 4951 <pre>{#syntax#}@hasField(comptime Container: type, comptime name: []const u8) bool{#endsyntax#}</pre> 4952 <p>Returns whether the field name of a struct, union, or enum exists.</p> 4953 <p> 4954 The result is a compile time constant. 4955 </p> 4956 <p> 4957 It does not include functions, variables, or constants. 4958 </p> 4959 {#see_also|@hasDecl#} 4960 {#header_close#} 4961 4962 {#header_open|@import#} 4963 <pre>{#syntax#}@import(comptime target: []const u8) anytype{#endsyntax#}</pre> 4964 <p>Imports the file at {#syntax#}target{#endsyntax#}, adding it to the compilation if it is not already 4965 added. {#syntax#}target{#endsyntax#} is either a relative path to another file from the file containing 4966 the {#syntax#}@import{#endsyntax#} call, or it is the name of a {#link|module|Compilation Model#}, with 4967 the import referring to the root source file of that module. Either way, the file path must end in 4968 either <code>.zig</code> (for a Zig source file) or <code>.zon</code> (for a ZON data file).</p> 4969 <p>If {#syntax#}target{#endsyntax#} refers to a Zig source file, then {#syntax#}@import{#endsyntax#} returns 4970 that file's {#link|corresponding struct type|Source File Structs#}, essentially as if the builtin call was 4971 replaced by {#syntax#}struct { FILE_CONTENTS }{#endsyntax#}. The return type is {#syntax#}type{#endsyntax#}.</p> 4972 <p>If {#syntax#}target{#endsyntax#} refers to a ZON file, then {#syntax#}@import{#endsyntax#} returns the value 4973 of the literal in the file. If there is an inferred {#link|result type|Result Types#}, then the return type 4974 is that type, and the ZON literal is interpreted as that type ({#link|Result Types#} are propagated through 4975 the ZON expression). Otherwise, the return type is the type of the equivalent Zig expression, essentially as 4976 if the builtin call was replaced by the ZON file contents.</p> 4977 <p>The following modules are always available for import:</p> 4978 <ul> 4979 <li>{#syntax#}@import("std"){#endsyntax#} - Zig Standard Library</li> 4980 <li>{#syntax#}@import("builtin"){#endsyntax#} - Target-specific information. The command <code>zig build-exe --show-builtin</code> outputs the source to stdout for reference.</li> 4981 <li>{#syntax#}@import("root"){#endsyntax#} - Alias for the root module. In typical project structures, this means it refers back to <code>src/main.zig</code>. 4982 </li> 4983 </ul> 4984 {#see_also|Compile Variables|@embedFile#} 4985 {#header_close#} 4986 4987 {#header_open|@inComptime#} 4988 <pre>{#syntax#}@inComptime() bool{#endsyntax#}</pre> 4989 <p> 4990 Returns whether the builtin was run in a {#syntax#}comptime{#endsyntax#} context. The result is a compile-time constant. 4991 </p> 4992 <p> 4993 This can be used to provide alternative, comptime-friendly implementations of functions. It should not be used, for instance, to exclude certain functions from being evaluated at comptime. 4994 </p> 4995 {#see_also|comptime#} 4996 {#header_close#} 4997 4998 {#header_open|@intCast#} 4999 <pre>{#syntax#}@intCast(int: anytype) anytype{#endsyntax#}</pre> 5000 <p> 5001 Converts an integer to another integer while keeping the same numerical value. 5002 The return type is the inferred result type. 5003 Attempting to convert a number which is out of range of the destination type results in 5004 safety-checked {#link|Illegal Behavior#}. 5005 </p> 5006 {#code|test_intCast_builtin.zig#} 5007 5008 <p> 5009 To truncate the significant bits of a number out of range of the destination type, use {#link|@truncate#}. 5010 </p> 5011 <p> 5012 If {#syntax#}T{#endsyntax#} is {#syntax#}comptime_int{#endsyntax#}, 5013 then this is semantically equivalent to {#link|Type Coercion#}. 5014 </p> 5015 {#header_close#} 5016 5017 {#header_open|@intFromBool#} 5018 <pre>{#syntax#}@intFromBool(value: bool) u1{#endsyntax#}</pre> 5019 <p> 5020 Converts {#syntax#}true{#endsyntax#} to {#syntax#}@as(u1, 1){#endsyntax#} and {#syntax#}false{#endsyntax#} to 5021 {#syntax#}@as(u1, 0){#endsyntax#}. 5022 </p> 5023 {#header_close#} 5024 5025 {#header_open|@intFromEnum#} 5026 <pre>{#syntax#}@intFromEnum(enum_or_tagged_union: anytype) anytype{#endsyntax#}</pre> 5027 <p> 5028 Converts an enumeration value into its integer tag type. When a tagged union is passed, 5029 the tag value is used as the enumeration value. 5030 </p> 5031 <p> 5032 If there is only one possible enum value, the result is a {#syntax#}comptime_int{#endsyntax#} 5033 known at {#link|comptime#}. 5034 </p> 5035 {#see_also|@enumFromInt#} 5036 {#header_close#} 5037 5038 {#header_open|@intFromError#} 5039 <pre>{#syntax#}@intFromError(err: anytype) std.meta.Int(.unsigned, @bitSizeOf(anyerror)){#endsyntax#}</pre> 5040 <p> 5041 Supports the following types: 5042 </p> 5043 <ul> 5044 <li>{#link|The Global Error Set#}</li> 5045 <li>{#link|Error Set Type#}</li> 5046 <li>{#link|Error Union Type#}</li> 5047 </ul> 5048 <p> 5049 Converts an error to the integer representation of an error. 5050 </p> 5051 <p> 5052 It is generally recommended to avoid this 5053 cast, as the integer representation of an error is not stable across source code changes. 5054 </p> 5055 {#see_also|@errorFromInt#} 5056 {#header_close#} 5057 5058 {#header_open|@intFromFloat#} 5059 <pre>{#syntax#}@intFromFloat(float: anytype) anytype{#endsyntax#}</pre> 5060 <p> 5061 Converts the integer part of a floating point number to the inferred result type. 5062 </p> 5063 <p> 5064 If the integer part of the floating point number cannot fit in the destination type, 5065 it invokes safety-checked {#link|Illegal Behavior#}. 5066 </p> 5067 {#see_also|@floatFromInt#} 5068 {#header_close#} 5069 5070 {#header_open|@intFromPtr#} 5071 <pre>{#syntax#}@intFromPtr(value: anytype) usize{#endsyntax#}</pre> 5072 <p> 5073 Converts {#syntax#}value{#endsyntax#} to a {#syntax#}usize{#endsyntax#} which is the address of the pointer. 5074 {#syntax#}value{#endsyntax#} can be {#syntax#}*T{#endsyntax#} or {#syntax#}?*T{#endsyntax#}. 5075 </p> 5076 <p>To convert the other way, use {#link|@ptrFromInt#}</p> 5077 {#header_close#} 5078 5079 {#header_open|@max#} 5080 <pre>{#syntax#}@max(...) T{#endsyntax#}</pre> 5081 <p> 5082 Takes two or more arguments and returns the biggest value included (the maximum). This builtin accepts integers, floats, and vectors of either. In the latter case, the operation is performed element wise. 5083 </p> 5084 <p> 5085 NaNs are handled as follows: return the biggest non-NaN value included. If all operands are NaN, return NaN. 5086 </p> 5087 {#see_also|@min|Vectors#} 5088 {#header_close#} 5089 5090 {#header_open|@memcpy#} 5091 <pre>{#syntax#}@memcpy(noalias dest, noalias source) void{#endsyntax#}</pre> 5092 <p>This function copies bytes from one region of memory to another.</p> 5093 <p>{#syntax#}dest{#endsyntax#} must be a mutable slice, a mutable pointer to an array, or 5094 a mutable many-item {#link|pointer|Pointers#}. It may have any 5095 alignment, and it may have any element type.</p> 5096 <p>{#syntax#}source{#endsyntax#} must be a slice, a pointer to 5097 an array, or a many-item {#link|pointer|Pointers#}. It may 5098 have any alignment, and it may have any element type.</p> 5099 <p>The {#syntax#}source{#endsyntax#} element type must have the same in-memory 5100 representation as the {#syntax#}dest{#endsyntax#} element type.</p> 5101 <p>Similar to {#link|for#} loops, at least one of {#syntax#}source{#endsyntax#} and 5102 {#syntax#}dest{#endsyntax#} must provide a length, and if two lengths are provided, 5103 they must be equal.</p> 5104 <p>Finally, the two memory regions must not overlap.</p> 5105 {#header_close#} 5106 5107 {#header_open|@memset#} 5108 <pre>{#syntax#}@memset(dest, elem) void{#endsyntax#}</pre> 5109 <p>This function sets all the elements of a memory region to {#syntax#}elem{#endsyntax#}.</p> 5110 <p>{#syntax#}dest{#endsyntax#} must be a mutable slice or a mutable pointer to an array. 5111 It may have any alignment, and it may have any element type.</p> 5112 <p>{#syntax#}elem{#endsyntax#} is coerced to the element type of {#syntax#}dest{#endsyntax#}.</p> 5113 <p>For securely zeroing out sensitive contents from memory, you should use 5114 {#syntax#}std.crypto.secureZero{#endsyntax#}</p> 5115 {#header_close#} 5116 5117 {#header_open|@memmove#} 5118 <pre>{#syntax#}@memmove(dest, source) void{#endsyntax#}</pre> 5119 <p>This function copies bytes from one region of memory to another, but unlike 5120 {#link|@memcpy#} the regions may overlap.</p> 5121 <p>{#syntax#}dest{#endsyntax#} must be a mutable slice, a mutable pointer to an array, or 5122 a mutable many-item {#link|pointer|Pointers#}. It may have any 5123 alignment, and it may have any element type.</p> 5124 <p>{#syntax#}source{#endsyntax#} must be a slice, a pointer to 5125 an array, or a many-item {#link|pointer|Pointers#}. It may 5126 have any alignment, and it may have any element type.</p> 5127 <p>The {#syntax#}source{#endsyntax#} element type must have the same in-memory 5128 representation as the {#syntax#}dest{#endsyntax#} element type.</p> 5129 <p>Similar to {#link|for#} loops, at least one of {#syntax#}source{#endsyntax#} and 5130 {#syntax#}dest{#endsyntax#} must provide a length, and if two lengths are provided, 5131 they must be equal.</p> 5132 {#header_close#} 5133 5134 {#header_open|@min#} 5135 <pre>{#syntax#}@min(...) T{#endsyntax#}</pre> 5136 <p> 5137 Takes two or more arguments and returns the smallest value included (the minimum). This builtin accepts integers, floats, and vectors of either. In the latter case, the operation is performed element wise. 5138 </p> 5139 <p> 5140 NaNs are handled as follows: return the smallest non-NaN value included. If all operands are NaN, return NaN. 5141 </p> 5142 {#see_also|@max|Vectors#} 5143 {#header_close#} 5144 5145 {#header_open|@wasmMemorySize#} 5146 <pre>{#syntax#}@wasmMemorySize(index: u32) usize{#endsyntax#}</pre> 5147 <p> 5148 This function returns the size of the Wasm memory identified by {#syntax#}index{#endsyntax#} as 5149 an unsigned value in units of Wasm pages. Note that each Wasm page is 64KB in size. 5150 </p> 5151 <p> 5152 This function is a low level intrinsic with no safety mechanisms usually useful for allocator 5153 designers targeting Wasm. So unless you are writing a new allocator from scratch, you should use 5154 something like {#syntax#}@import("std").heap.WasmPageAllocator{#endsyntax#}. 5155 </p> 5156 {#see_also|@wasmMemoryGrow#} 5157 {#header_close#} 5158 5159 {#header_open|@wasmMemoryGrow#} 5160 <pre>{#syntax#}@wasmMemoryGrow(index: u32, delta: usize) isize{#endsyntax#}</pre> 5161 <p> 5162 This function increases the size of the Wasm memory identified by {#syntax#}index{#endsyntax#} by 5163 {#syntax#}delta{#endsyntax#} in units of unsigned number of Wasm pages. Note that each Wasm page 5164 is 64KB in size. On success, returns previous memory size; on failure, if the allocation fails, 5165 returns -1. 5166 </p> 5167 <p> 5168 This function is a low level intrinsic with no safety mechanisms usually useful for allocator 5169 designers targeting Wasm. So unless you are writing a new allocator from scratch, you should use 5170 something like {#syntax#}@import("std").heap.WasmPageAllocator{#endsyntax#}. 5171 </p> 5172 {#code|test_wasmMemoryGrow_builtin.zig#} 5173 5174 {#see_also|@wasmMemorySize#} 5175 {#header_close#} 5176 5177 {#header_open|@mod#} 5178 <pre>{#syntax#}@mod(numerator: T, denominator: T) T{#endsyntax#}</pre> 5179 <p> 5180 Modulus division. For unsigned integers this is the same as 5181 {#syntax#}numerator % denominator{#endsyntax#}. Caller guarantees {#syntax#}denominator != 0{#endsyntax#}, otherwise the 5182 operation will result in a {#link|Remainder Division by Zero#} when runtime safety checks are enabled. 5183 </p> 5184 <ul> 5185 <li>{#syntax#}@mod(-5, 3) == 1{#endsyntax#}</li> 5186 <li>{#syntax#}(@divFloor(a, b) * b) + @mod(a, b) == a{#endsyntax#}</li> 5187 </ul> 5188 <p>For a function that returns an error code, see {#syntax#}@import("std").math.mod{#endsyntax#}.</p> 5189 {#see_also|@rem#} 5190 {#header_close#} 5191 5192 {#header_open|@mulWithOverflow#} 5193 <pre>{#syntax#}@mulWithOverflow(a: anytype, b: anytype) struct { @TypeOf(a, b), u1 }{#endsyntax#}</pre> 5194 <p> 5195 Performs {#syntax#}a * b{#endsyntax#} and returns a tuple with the result and a possible overflow bit. 5196 </p> 5197 {#header_close#} 5198 5199 {#header_open|@panic#} 5200 <pre>{#syntax#}@panic(message: []const u8) noreturn{#endsyntax#}</pre> 5201 <p> 5202 Invokes the panic handler function. By default the panic handler function 5203 calls the public {#syntax#}panic{#endsyntax#} function exposed in the root source file, or 5204 if there is not one specified, the {#syntax#}std.builtin.default_panic{#endsyntax#} 5205 function from {#syntax#}std/builtin.zig{#endsyntax#}. 5206 </p> 5207 <p>Generally it is better to use {#syntax#}@import("std").debug.panic{#endsyntax#}. 5208 However, {#syntax#}@panic{#endsyntax#} can be useful for 2 scenarios: 5209 </p> 5210 <ul> 5211 <li>From library code, calling the programmer's panic function if they exposed one in the root source file.</li> 5212 <li>When mixing C and Zig code, calling the canonical panic implementation across multiple .o files.</li> 5213 </ul> 5214 {#see_also|Panic Handler#} 5215 {#header_close#} 5216 5217 {#header_open|@popCount#} 5218 <pre>{#syntax#}@popCount(operand: anytype) anytype{#endsyntax#}</pre> 5219 <p>{#syntax#}@TypeOf(operand){#endsyntax#} must be an integer type.</p> 5220 <p>{#syntax#}operand{#endsyntax#} may be an {#link|integer|Integers#} or {#link|vector|Vectors#}.</p> 5221 <p> 5222 Counts the number of bits set in an integer - "population count". 5223 </p> 5224 <p> 5225 The return type is an unsigned integer or vector of unsigned integers with the minimum number 5226 of bits that can represent the bit count of the integer type. 5227 </p> 5228 {#see_also|@ctz|@clz#} 5229 {#header_close#} 5230 5231 {#header_open|@prefetch#} 5232 <pre>{#syntax#}@prefetch(ptr: anytype, comptime options: PrefetchOptions) void{#endsyntax#}</pre> 5233 <p> 5234 This builtin tells the compiler to emit a prefetch instruction if supported by the 5235 target CPU. If the target CPU does not support the requested prefetch instruction, 5236 this builtin is a no-op. This function has no effect on the behavior of the program, 5237 only on the performance characteristics. 5238 </p> 5239 <p> 5240 The {#syntax#}ptr{#endsyntax#} argument may be any pointer type and determines the memory 5241 address to prefetch. This function does not dereference the pointer, it is perfectly legal 5242 to pass a pointer to invalid memory to this function and no Illegal Behavior will result. 5243 </p> 5244 <p>{#syntax#}PrefetchOptions{#endsyntax#} can be found with {#syntax#}@import("std").builtin.PrefetchOptions{#endsyntax#}.</p> 5245 {#header_close#} 5246 5247 {#header_open|@ptrCast#} 5248 <pre>{#syntax#}@ptrCast(value: anytype) anytype{#endsyntax#}</pre> 5249 <p> 5250 Converts a pointer of one type to a pointer of another type. The return type is the inferred result type. 5251 </p> 5252 <p> 5253 {#link|Optional Pointers#} are allowed. Casting an optional pointer which is {#link|null#} 5254 to a non-optional pointer invokes safety-checked {#link|Illegal Behavior#}. 5255 </p> 5256 <p> 5257 {#syntax#}@ptrCast{#endsyntax#} cannot be used for: 5258 </p> 5259 <ul> 5260 <li>Removing {#syntax#}const{#endsyntax#} qualifier, use {#link|@constCast#}.</li> 5261 <li>Removing {#syntax#}volatile{#endsyntax#} qualifier, use {#link|@volatileCast#}.</li> 5262 <li>Changing pointer address space, use {#link|@addrSpaceCast#}.</li> 5263 <li>Increasing pointer alignment, use {#link|@alignCast#}.</li> 5264 <li>Casting a non-slice pointer to a slice, use slicing syntax {#syntax#}ptr[start..end]{#endsyntax#}.</li> 5265 </ul> 5266 {#header_close#} 5267 5268 {#header_open|@ptrFromInt#} 5269 <pre>{#syntax#}@ptrFromInt(address: usize) anytype{#endsyntax#}</pre> 5270 <p> 5271 Converts an integer to a {#link|pointer|Pointers#}. The return type is the inferred result type. 5272 To convert the other way, use {#link|@intFromPtr#}. Casting an address of 0 to a destination type 5273 which in not {#link|optional|Optional Pointers#} and does not have the {#syntax#}allowzero{#endsyntax#} attribute will result in a 5274 {#link|Pointer Cast Invalid Null#} panic when runtime safety checks are enabled. 5275 </p> 5276 <p> 5277 If the destination pointer type does not allow address zero and {#syntax#}address{#endsyntax#} 5278 is zero, this invokes safety-checked {#link|Illegal Behavior#}. 5279 </p> 5280 {#header_close#} 5281 5282 {#header_open|@rem#} 5283 <pre>{#syntax#}@rem(numerator: T, denominator: T) T{#endsyntax#}</pre> 5284 <p> 5285 Remainder division. For unsigned integers this is the same as 5286 {#syntax#}numerator % denominator{#endsyntax#}. Caller guarantees {#syntax#}denominator != 0{#endsyntax#}, otherwise the 5287 operation will result in a {#link|Remainder Division by Zero#} when runtime safety checks are enabled. 5288 </p> 5289 <ul> 5290 <li>{#syntax#}@rem(-5, 3) == -2{#endsyntax#}</li> 5291 <li>{#syntax#}(@divTrunc(a, b) * b) + @rem(a, b) == a{#endsyntax#}</li> 5292 </ul> 5293 <p>For a function that returns an error code, see {#syntax#}@import("std").math.rem{#endsyntax#}.</p> 5294 {#see_also|@mod#} 5295 {#header_close#} 5296 5297 {#header_open|@returnAddress#} 5298 <pre>{#syntax#}@returnAddress() usize{#endsyntax#}</pre> 5299 <p> 5300 This function returns the address of the next machine code instruction that will be executed 5301 when the current function returns. 5302 </p> 5303 <p> 5304 The implications of this are target-specific and not consistent across 5305 all platforms. 5306 </p> 5307 <p> 5308 This function is only valid within function scope. If the function gets inlined into 5309 a calling function, the returned address will apply to the calling function. 5310 </p> 5311 {#header_close#} 5312 5313 {#header_open|@select#} 5314 <pre>{#syntax#}@select(comptime T: type, pred: @Vector(len, bool), a: @Vector(len, T), b: @Vector(len, T)) @Vector(len, T){#endsyntax#}</pre> 5315 <p> 5316 Selects values element-wise from {#syntax#}a{#endsyntax#} or {#syntax#}b{#endsyntax#} based on {#syntax#}pred{#endsyntax#}. If {#syntax#}pred[i]{#endsyntax#} is {#syntax#}true{#endsyntax#}, the corresponding element in the result will be {#syntax#}a[i]{#endsyntax#} and otherwise {#syntax#}b[i]{#endsyntax#}. 5317 </p> 5318 {#see_also|Vectors#} 5319 {#header_close#} 5320 5321 {#header_open|@setEvalBranchQuota#} 5322 <pre>{#syntax#}@setEvalBranchQuota(comptime new_quota: u32) void{#endsyntax#}</pre> 5323 <p> 5324 Increase the maximum number of backwards branches that compile-time code 5325 execution can use before giving up and making a compile error. 5326 </p> 5327 <p> 5328 If the {#syntax#}new_quota{#endsyntax#} is smaller than the default quota ({#syntax#}1000{#endsyntax#}) or 5329 a previously explicitly set quota, it is ignored. 5330 </p> 5331 <p> 5332 Example: 5333 </p> 5334 {#code|test_without_setEvalBranchQuota_builtin.zig#} 5335 5336 <p>Now we use {#syntax#}@setEvalBranchQuota{#endsyntax#}:</p> 5337 {#code|test_setEvalBranchQuota_builtin.zig#} 5338 5339 5340 {#see_also|comptime#} 5341 {#header_close#} 5342 5343 {#header_open|@setFloatMode#} 5344 <pre>{#syntax#}@setFloatMode(comptime mode: FloatMode) void{#endsyntax#}</pre> 5345 <p>Changes the current scope's rules about how floating point operations are defined.</p> 5346 <ul> 5347 <li> 5348 {#syntax#}Strict{#endsyntax#} (default) - Floating point operations follow strict IEEE compliance. 5349 </li> 5350 <li> 5351 {#syntax#}Optimized{#endsyntax#} - Floating point operations may do all of the following: 5352 <ul> 5353 <li>Assume the arguments and result are not NaN. Optimizations are required to retain legal behavior over NaNs, but the value of the result is undefined.</li> 5354 <li>Assume the arguments and result are not +/-Inf. Optimizations are required to retain legal behavior over +/-Inf, but the value of the result is undefined.</li> 5355 <li>Treat the sign of a zero argument or result as insignificant.</li> 5356 <li>Use the reciprocal of an argument rather than perform division.</li> 5357 <li>Perform floating-point contraction (e.g. fusing a multiply followed by an addition into a fused multiply-add).</li> 5358 <li>Perform algebraically equivalent transformations that may change results in floating point (e.g. reassociate).</li> 5359 </ul> 5360 This is equivalent to <code>-ffast-math</code> in GCC. 5361 </li> 5362 </ul> 5363 <p> 5364 The floating point mode is inherited by child scopes, and can be overridden in any scope. 5365 You can set the floating point mode in a struct or module scope by using a comptime block. 5366 </p> 5367 <p>{#syntax#}FloatMode{#endsyntax#} can be found with {#syntax#}@import("std").builtin.FloatMode{#endsyntax#}.</p> 5368 {#see_also|Floating Point Operations#} 5369 {#header_close#} 5370 5371 {#header_open|@setRuntimeSafety#} 5372 <pre>{#syntax#}@setRuntimeSafety(comptime safety_on: bool) void{#endsyntax#}</pre> 5373 <p> 5374 Sets whether runtime safety checks are enabled for the scope that contains the function call. 5375 </p> 5376 {#code|test_setRuntimeSafety_builtin.zig#} 5377 5378 <p>Note: it is <a href="https://github.com/ziglang/zig/issues/978">planned</a> to replace 5379 {#syntax#}@setRuntimeSafety{#endsyntax#} with <code>@optimizeFor</code></p> 5380 5381 {#header_close#} 5382 5383 {#header_open|@shlExact#} 5384 <pre>{#syntax#}@shlExact(value: T, shift_amt: Log2T) T{#endsyntax#}</pre> 5385 <p> 5386 Performs the left shift operation ({#syntax#}<<{#endsyntax#}). 5387 For unsigned integers, the result is {#link|undefined#} if any 1 bits 5388 are shifted out. For signed integers, the result is {#link|undefined#} if 5389 any bits that disagree with the resultant sign bit are shifted out. 5390 </p> 5391 <p> 5392 The type of {#syntax#}shift_amt{#endsyntax#} is an unsigned integer with {#syntax#}log2(@typeInfo(T).int.bits){#endsyntax#} bits. 5393 This is because {#syntax#}shift_amt >= @typeInfo(T).int.bits{#endsyntax#} triggers safety-checked {#link|Illegal Behavior#}. 5394 </p> 5395 <p> 5396 {#syntax#}comptime_int{#endsyntax#} is modeled as an integer with an infinite number of bits, 5397 meaning that in such case, {#syntax#}@shlExact{#endsyntax#} always produces a result and 5398 cannot produce a compile error. 5399 </p> 5400 {#see_also|@shrExact|@shlWithOverflow#} 5401 {#header_close#} 5402 5403 {#header_open|@shlWithOverflow#} 5404 <pre>{#syntax#}@shlWithOverflow(a: anytype, shift_amt: Log2T) struct { @TypeOf(a), u1 }{#endsyntax#}</pre> 5405 <p> 5406 Performs {#syntax#}a << b{#endsyntax#} and returns a tuple with the result and a possible overflow bit. 5407 </p> 5408 <p> 5409 The type of {#syntax#}shift_amt{#endsyntax#} is an unsigned integer with {#syntax#}log2(@typeInfo(@TypeOf(a)).int.bits){#endsyntax#} bits. 5410 This is because {#syntax#}shift_amt >= @typeInfo(@TypeOf(a)).int.bits{#endsyntax#} triggers safety-checked {#link|Illegal Behavior#}. 5411 </p> 5412 {#see_also|@shlExact|@shrExact#} 5413 {#header_close#} 5414 5415 {#header_open|@shrExact#} 5416 <pre>{#syntax#}@shrExact(value: T, shift_amt: Log2T) T{#endsyntax#}</pre> 5417 <p> 5418 Performs the right shift operation ({#syntax#}>>{#endsyntax#}). Caller guarantees 5419 that the shift will not shift any 1 bits out. 5420 </p> 5421 <p> 5422 The type of {#syntax#}shift_amt{#endsyntax#} is an unsigned integer with {#syntax#}log2(@typeInfo(T).int.bits){#endsyntax#} bits. 5423 This is because {#syntax#}shift_amt >= @typeInfo(T).int.bits{#endsyntax#} triggers safety-checked {#link|Illegal Behavior#}. 5424 </p> 5425 {#see_also|@shlExact|@shlWithOverflow#} 5426 {#header_close#} 5427 5428 {#header_open|@shuffle#} 5429 <pre>{#syntax#}@shuffle(comptime E: type, a: @Vector(a_len, E), b: @Vector(b_len, E), comptime mask: @Vector(mask_len, i32)) @Vector(mask_len, E){#endsyntax#}</pre> 5430 <p> 5431 Constructs a new {#link|vector|Vectors#} by selecting elements from {#syntax#}a{#endsyntax#} and 5432 {#syntax#}b{#endsyntax#} based on {#syntax#}mask{#endsyntax#}. 5433 </p> 5434 <p> 5435 Each element in {#syntax#}mask{#endsyntax#} selects an element from either {#syntax#}a{#endsyntax#} or 5436 {#syntax#}b{#endsyntax#}. Positive numbers select from {#syntax#}a{#endsyntax#} starting at 0. 5437 Negative values select from {#syntax#}b{#endsyntax#}, starting at {#syntax#}-1{#endsyntax#} and going down. 5438 It is recommended to use the {#syntax#}~{#endsyntax#} operator for indexes from {#syntax#}b{#endsyntax#} 5439 so that both indexes can start from {#syntax#}0{#endsyntax#} (i.e. {#syntax#}~@as(i32, 0){#endsyntax#} is 5440 {#syntax#}-1{#endsyntax#}). 5441 </p> 5442 <p> 5443 For each element of {#syntax#}mask{#endsyntax#}, if it or the selected value from 5444 {#syntax#}a{#endsyntax#} or {#syntax#}b{#endsyntax#} is {#syntax#}undefined{#endsyntax#}, 5445 then the resulting element is {#syntax#}undefined{#endsyntax#}. 5446 </p> 5447 <p> 5448 {#syntax#}a_len{#endsyntax#} and {#syntax#}b_len{#endsyntax#} may differ in length. Out-of-bounds element 5449 indexes in {#syntax#}mask{#endsyntax#} result in compile errors. 5450 </p> 5451 <p> 5452 If {#syntax#}a{#endsyntax#} or {#syntax#}b{#endsyntax#} is {#syntax#}undefined{#endsyntax#}, it 5453 is equivalent to a vector of all {#syntax#}undefined{#endsyntax#} with the same length as the other vector. 5454 If both vectors are {#syntax#}undefined{#endsyntax#}, {#syntax#}@shuffle{#endsyntax#} returns 5455 a vector with all elements {#syntax#}undefined{#endsyntax#}. 5456 </p> 5457 <p> 5458 {#syntax#}E{#endsyntax#} must be an {#link|integer|Integers#}, {#link|float|Floats#}, 5459 {#link|pointer|Pointers#}, or {#syntax#}bool{#endsyntax#}. The mask may be any vector length, and its 5460 length determines the result length. 5461 </p> 5462 {#code|test_shuffle_builtin.zig#} 5463 5464 {#see_also|Vectors#} 5465 {#header_close#} 5466 5467 {#header_open|@sizeOf#} 5468 <pre>{#syntax#}@sizeOf(comptime T: type) comptime_int{#endsyntax#}</pre> 5469 <p> 5470 This function returns the number of bytes it takes to store {#syntax#}T{#endsyntax#} in memory. 5471 The result is a target-specific compile time constant. 5472 </p> 5473 <p> 5474 This size may contain padding bytes. If there were two consecutive T in memory, the padding would be the offset 5475 in bytes between element at index 0 and the element at index 1. For {#link|integer|Integers#}, 5476 consider whether you want to use {#syntax#}@sizeOf(T){#endsyntax#} or 5477 {#syntax#}@typeInfo(T).int.bits{#endsyntax#}. 5478 </p> 5479 <p> 5480 This function measures the size at runtime. For types that are disallowed at runtime, such as 5481 {#syntax#}comptime_int{#endsyntax#} and {#syntax#}type{#endsyntax#}, the result is {#syntax#}0{#endsyntax#}. 5482 </p> 5483 {#see_also|@bitSizeOf|@typeInfo#} 5484 {#header_close#} 5485 5486 {#header_open|@splat#} 5487 <pre>{#syntax#}@splat(scalar: anytype) anytype{#endsyntax#}</pre> 5488 <p> 5489 Produces an array or vector where each element is the value 5490 {#syntax#}scalar{#endsyntax#}. The return type and thus the length of the 5491 vector is inferred. 5492 </p> 5493 {#code|test_splat_builtin.zig#} 5494 5495 <p> 5496 {#syntax#}scalar{#endsyntax#} must be an {#link|integer|Integers#}, {#link|bool|Primitive Types#}, 5497 {#link|float|Floats#}, or {#link|pointer|Pointers#}. 5498 </p> 5499 {#see_also|Vectors|@shuffle#} 5500 {#header_close#} 5501 5502 {#header_open|@reduce#} 5503 <pre>{#syntax#}@reduce(comptime op: std.builtin.ReduceOp, value: anytype) E{#endsyntax#}</pre> 5504 <p> 5505 Transforms a {#link|vector|Vectors#} into a scalar value (of type <code>E</code>) 5506 by performing a sequential horizontal reduction of its elements using the 5507 specified operator {#syntax#}op{#endsyntax#}. 5508 </p> 5509 <p> 5510 Not every operator is available for every vector element type: 5511 </p> 5512 <ul> 5513 <li>Every operator is available for {#link|integer|Integers#} vectors.</li> 5514 <li>{#syntax#}.And{#endsyntax#}, {#syntax#}.Or{#endsyntax#}, 5515 {#syntax#}.Xor{#endsyntax#} are additionally available for 5516 {#syntax#}bool{#endsyntax#} vectors,</li> 5517 <li>{#syntax#}.Min{#endsyntax#}, {#syntax#}.Max{#endsyntax#}, 5518 {#syntax#}.Add{#endsyntax#}, {#syntax#}.Mul{#endsyntax#} are 5519 additionally available for {#link|floating point|Floats#} vectors,</li> 5520 </ul> 5521 <p> 5522 Note that {#syntax#}.Add{#endsyntax#} and {#syntax#}.Mul{#endsyntax#} 5523 reductions on integral types are wrapping; when applied on floating point 5524 types the operation associativity is preserved, unless the float mode is 5525 set to {#syntax#}Optimized{#endsyntax#}. 5526 </p> 5527 {#code|test_reduce_builtin.zig#} 5528 5529 {#see_also|Vectors|@setFloatMode#} 5530 {#header_close#} 5531 5532 {#header_open|@src#} 5533 <pre>{#syntax#}@src() std.builtin.SourceLocation{#endsyntax#}</pre> 5534 <p> 5535 Returns a {#syntax#}SourceLocation{#endsyntax#} struct representing the function's name and location in the source code. This must be called in a function. 5536 </p> 5537 {#code|test_src_builtin.zig#} 5538 5539 {#header_close#} 5540 {#header_open|@sqrt#} 5541 <pre>{#syntax#}@sqrt(value: anytype) @TypeOf(value){#endsyntax#}</pre> 5542 <p> 5543 Performs the square root of a floating point number. Uses a dedicated hardware instruction 5544 when available. 5545 </p> 5546 <p> 5547 Supports {#link|Floats#} and {#link|Vectors#} of floats. 5548 </p> 5549 {#header_close#} 5550 {#header_open|@sin#} 5551 <pre>{#syntax#}@sin(value: anytype) @TypeOf(value){#endsyntax#}</pre> 5552 <p> 5553 Sine trigonometric function on a floating point number in radians. Uses a dedicated hardware instruction 5554 when available. 5555 </p> 5556 <p> 5557 Supports {#link|Floats#} and {#link|Vectors#} of floats. 5558 </p> 5559 {#header_close#} 5560 5561 {#header_open|@cos#} 5562 <pre>{#syntax#}@cos(value: anytype) @TypeOf(value){#endsyntax#}</pre> 5563 <p> 5564 Cosine trigonometric function on a floating point number in radians. Uses a dedicated hardware instruction 5565 when available. 5566 </p> 5567 <p> 5568 Supports {#link|Floats#} and {#link|Vectors#} of floats. 5569 </p> 5570 {#header_close#} 5571 5572 {#header_open|@tan#} 5573 <pre>{#syntax#}@tan(value: anytype) @TypeOf(value){#endsyntax#}</pre> 5574 <p> 5575 Tangent trigonometric function on a floating point number in radians. 5576 Uses a dedicated hardware instruction when available. 5577 </p> 5578 <p> 5579 Supports {#link|Floats#} and {#link|Vectors#} of floats. 5580 </p> 5581 {#header_close#} 5582 5583 {#header_open|@exp#} 5584 <pre>{#syntax#}@exp(value: anytype) @TypeOf(value){#endsyntax#}</pre> 5585 <p> 5586 Base-e exponential function on a floating point number. Uses a dedicated hardware instruction 5587 when available. 5588 </p> 5589 <p> 5590 Supports {#link|Floats#} and {#link|Vectors#} of floats. 5591 </p> 5592 {#header_close#} 5593 {#header_open|@exp2#} 5594 <pre>{#syntax#}@exp2(value: anytype) @TypeOf(value){#endsyntax#}</pre> 5595 <p> 5596 Base-2 exponential function on a floating point number. Uses a dedicated hardware instruction 5597 when available. 5598 </p> 5599 <p> 5600 Supports {#link|Floats#} and {#link|Vectors#} of floats. 5601 </p> 5602 {#header_close#} 5603 {#header_open|@log#} 5604 <pre>{#syntax#}@log(value: anytype) @TypeOf(value){#endsyntax#}</pre> 5605 <p> 5606 Returns the natural logarithm of a floating point number. Uses a dedicated hardware instruction 5607 when available. 5608 </p> 5609 <p> 5610 Supports {#link|Floats#} and {#link|Vectors#} of floats. 5611 </p> 5612 {#header_close#} 5613 {#header_open|@log2#} 5614 <pre>{#syntax#}@log2(value: anytype) @TypeOf(value){#endsyntax#}</pre> 5615 <p> 5616 Returns the logarithm to the base 2 of a floating point number. Uses a dedicated hardware instruction 5617 when available. 5618 </p> 5619 <p> 5620 Supports {#link|Floats#} and {#link|Vectors#} of floats. 5621 </p> 5622 {#header_close#} 5623 {#header_open|@log10#} 5624 <pre>{#syntax#}@log10(value: anytype) @TypeOf(value){#endsyntax#}</pre> 5625 <p> 5626 Returns the logarithm to the base 10 of a floating point number. Uses a dedicated hardware instruction 5627 when available. 5628 </p> 5629 <p> 5630 Supports {#link|Floats#} and {#link|Vectors#} of floats. 5631 </p> 5632 {#header_close#} 5633 {#header_open|@abs#} 5634 <pre>{#syntax#}@abs(value: anytype) anytype{#endsyntax#}</pre> 5635 <p> 5636 Returns the absolute value of an integer or a floating point number. Uses a dedicated hardware instruction 5637 when available. 5638 5639 The return type is always an unsigned integer of the same bit width as the operand if the operand is an integer. 5640 Unsigned integer operands are supported. The builtin cannot overflow for signed integer operands. 5641 </p> 5642 <p> 5643 Supports {#link|Floats#}, {#link|Integers#} and {#link|Vectors#} of floats or integers. 5644 </p> 5645 {#header_close#} 5646 {#header_open|@floor#} 5647 <pre>{#syntax#}@floor(value: anytype) @TypeOf(value){#endsyntax#}</pre> 5648 <p> 5649 Returns the largest integral value not greater than the given floating point number. 5650 Uses a dedicated hardware instruction when available. 5651 </p> 5652 <p> 5653 Supports {#link|Floats#} and {#link|Vectors#} of floats. 5654 </p> 5655 {#header_close#} 5656 {#header_open|@ceil#} 5657 <pre>{#syntax#}@ceil(value: anytype) @TypeOf(value){#endsyntax#}</pre> 5658 <p> 5659 Returns the smallest integral value not less than the given floating point number. 5660 Uses a dedicated hardware instruction when available. 5661 </p> 5662 <p> 5663 Supports {#link|Floats#} and {#link|Vectors#} of floats. 5664 </p> 5665 {#header_close#} 5666 {#header_open|@trunc#} 5667 <pre>{#syntax#}@trunc(value: anytype) @TypeOf(value){#endsyntax#}</pre> 5668 <p> 5669 Rounds the given floating point number to an integer, towards zero. 5670 Uses a dedicated hardware instruction when available. 5671 </p> 5672 <p> 5673 Supports {#link|Floats#} and {#link|Vectors#} of floats. 5674 </p> 5675 {#header_close#} 5676 {#header_open|@round#} 5677 <pre>{#syntax#}@round(value: anytype) @TypeOf(value){#endsyntax#}</pre> 5678 <p> 5679 Rounds the given floating point number to the nearest integer. If two integers are equally close, rounds away from zero. 5680 Uses a dedicated hardware instruction when available. 5681 </p> 5682 {#code|test_round_builtin.zig#} 5683 5684 <p> 5685 Supports {#link|Floats#} and {#link|Vectors#} of floats. 5686 </p> 5687 {#header_close#} 5688 5689 {#header_open|@subWithOverflow#} 5690 <pre>{#syntax#}@subWithOverflow(a: anytype, b: anytype) struct { @TypeOf(a, b), u1 }{#endsyntax#}</pre> 5691 <p> 5692 Performs {#syntax#}a - b{#endsyntax#} and returns a tuple with the result and a possible overflow bit. 5693 </p> 5694 {#header_close#} 5695 5696 {#header_open|@tagName#} 5697 <pre>{#syntax#}@tagName(value: anytype) [:0]const u8{#endsyntax#}</pre> 5698 <p> 5699 Converts an enum value or union value to a string literal representing the name.</p><p>If the enum is non-exhaustive and the tag value does not map to a name, it invokes safety-checked {#link|Illegal Behavior#}. 5700 </p> 5701 {#header_close#} 5702 5703 {#header_open|@This#} 5704 <pre>{#syntax#}@This() type{#endsyntax#}</pre> 5705 <p> 5706 Returns the innermost struct, enum, or union that this function call is inside. 5707 This can be useful for an anonymous struct that needs to refer to itself: 5708 </p> 5709 {#code|test_this_builtin.zig#} 5710 5711 <p> 5712 When {#syntax#}@This(){#endsyntax#} is used at file scope, it returns a reference to the 5713 struct that corresponds to the current file. 5714 </p> 5715 {#header_close#} 5716 5717 {#header_open|@trap#} 5718 <pre>{#syntax#}@trap() noreturn{#endsyntax#}</pre> 5719 <p> 5720 This function inserts a platform-specific trap/jam instruction which can be used to exit the program abnormally. 5721 This may be implemented by explicitly emitting an invalid instruction which may cause an illegal instruction exception of some sort. 5722 Unlike for {#syntax#}@breakpoint(){#endsyntax#}, execution does not continue after this point. 5723 </p> 5724 <p> 5725 Outside function scope, this builtin causes a compile error. 5726 </p> 5727 {#see_also|@breakpoint#} 5728 {#header_close#} 5729 5730 {#header_open|@truncate#} 5731 <pre>{#syntax#}@truncate(integer: anytype) anytype{#endsyntax#}</pre> 5732 <p> 5733 This function truncates bits from an integer type, resulting in a smaller 5734 or same-sized integer type. The return type is the inferred result type. 5735 </p> 5736 <p> 5737 This function always truncates the significant bits of the integer, regardless 5738 of endianness on the target platform. 5739 </p> 5740 <p> 5741 Calling {#syntax#}@truncate{#endsyntax#} on a number out of range of the destination type is well defined and working code: 5742 </p> 5743 {#code|test_truncate_builtin.zig#} 5744 5745 <p> 5746 Use {#link|@intCast#} to convert numbers guaranteed to fit the destination type. 5747 </p> 5748 {#header_close#} 5749 5750 {#header_open|@Type#} 5751 <pre>{#syntax#}@Type(comptime info: std.builtin.Type) type{#endsyntax#}</pre> 5752 <p> 5753 This function is the inverse of {#link|@typeInfo#}. It reifies type information 5754 into a {#syntax#}type{#endsyntax#}. 5755 </p> 5756 <p> 5757 It is available for the following types: 5758 </p> 5759 <ul> 5760 <li>{#syntax#}type{#endsyntax#}</li> 5761 <li>{#syntax#}noreturn{#endsyntax#}</li> 5762 <li>{#syntax#}void{#endsyntax#}</li> 5763 <li>{#syntax#}bool{#endsyntax#}</li> 5764 <li>{#link|Integers#} - The maximum bit count for an integer type is {#syntax#}65535{#endsyntax#}.</li> 5765 <li>{#link|Floats#}</li> 5766 <li>{#link|Pointers#}</li> 5767 <li>{#syntax#}comptime_int{#endsyntax#}</li> 5768 <li>{#syntax#}comptime_float{#endsyntax#}</li> 5769 <li>{#syntax#}@TypeOf(undefined){#endsyntax#}</li> 5770 <li>{#syntax#}@TypeOf(null){#endsyntax#}</li> 5771 <li>{#link|Arrays#}</li> 5772 <li>{#link|Optionals#}</li> 5773 <li>{#link|Error Set Type#}</li> 5774 <li>{#link|Error Union Type#}</li> 5775 <li>{#link|Vectors#}</li> 5776 <li>{#link|opaque#}</li> 5777 <li>{#syntax#}anyframe{#endsyntax#}</li> 5778 <li>{#link|struct#}</li> 5779 <li>{#link|enum#}</li> 5780 <li>{#link|Enum Literals#}</li> 5781 <li>{#link|union#}</li> 5782 <li>{#link|Functions#}</li> 5783 </ul> 5784 {#header_close#} 5785 {#header_open|@typeInfo#} 5786 <pre>{#syntax#}@typeInfo(comptime T: type) std.builtin.Type{#endsyntax#}</pre> 5787 <p> 5788 Provides type reflection. 5789 </p> 5790 <p> 5791 Type information of {#link|structs|struct#}, {#link|unions|union#}, {#link|enums|enum#}, and 5792 {#link|error sets|Error Set Type#} has fields which are guaranteed to be in the same 5793 order as appearance in the source file. 5794 </p> 5795 <p> 5796 Type information of {#link|structs|struct#}, {#link|unions|union#}, {#link|enums|enum#}, and 5797 {#link|opaques|opaque#} has declarations, which are also guaranteed to be in the same 5798 order as appearance in the source file. 5799 </p> 5800 {#header_close#} 5801 5802 {#header_open|@typeName#} 5803 <pre>{#syntax#}@typeName(T: type) *const [N:0]u8{#endsyntax#}</pre> 5804 <p> 5805 This function returns the string representation of a type, as 5806 an array. It is equivalent to a string literal of the type name. 5807 The returned type name is fully qualified with the parent namespace included 5808 as part of the type name with a series of dots. 5809 </p> 5810 {#header_close#} 5811 5812 {#header_open|@TypeOf#} 5813 <pre>{#syntax#}@TypeOf(...) type{#endsyntax#}</pre> 5814 <p> 5815 {#syntax#}@TypeOf{#endsyntax#} is a special builtin function that takes any (non-zero) number of expressions 5816 as parameters and returns the type of the result, using {#link|Peer Type Resolution#}. 5817 </p> 5818 <p> 5819 The expressions are evaluated, however they are guaranteed to have no <em>runtime</em> side-effects: 5820 </p> 5821 {#code|test_TypeOf_builtin.zig#} 5822 5823 {#header_close#} 5824 5825 {#header_open|@unionInit#} 5826 <pre>{#syntax#}@unionInit(comptime Union: type, comptime active_field_name: []const u8, init_expr) Union{#endsyntax#}</pre> 5827 <p> 5828 This is the same thing as {#link|union#} initialization syntax, except that the field name is a 5829 {#link|comptime#}-known value rather than an identifier token. 5830 </p> 5831 <p> 5832 {#syntax#}@unionInit{#endsyntax#} forwards its {#link|result location|Result Location Semantics#} to {#syntax#}init_expr{#endsyntax#}. 5833 </p> 5834 {#header_close#} 5835 5836 5837 {#header_open|@Vector#} 5838 <pre>{#syntax#}@Vector(len: comptime_int, Element: type) type{#endsyntax#}</pre> 5839 <p>Creates {#link|Vectors#}.</p> 5840 {#header_close#} 5841 5842 {#header_open|@volatileCast#} 5843 <pre>{#syntax#}@volatileCast(value: anytype) DestType{#endsyntax#}</pre> 5844 <p> 5845 Remove {#syntax#}volatile{#endsyntax#} qualifier from a pointer. 5846 </p> 5847 {#header_close#} 5848 5849 {#header_open|@workGroupId#} 5850 <pre>{#syntax#}@workGroupId(comptime dimension: u32) u32{#endsyntax#}</pre> 5851 <p> 5852 Returns the index of the work group in the current kernel invocation in dimension {#syntax#}dimension{#endsyntax#}. 5853 </p> 5854 {#header_close#} 5855 5856 {#header_open|@workGroupSize#} 5857 <pre>{#syntax#}@workGroupSize(comptime dimension: u32) u32{#endsyntax#}</pre> 5858 <p> 5859 Returns the number of work items that a work group has in dimension {#syntax#}dimension{#endsyntax#}. 5860 </p> 5861 {#header_close#} 5862 5863 {#header_open|@workItemId#} 5864 <pre>{#syntax#}@workItemId(comptime dimension: u32) u32{#endsyntax#}</pre> 5865 <p> 5866 Returns the index of the work item in the work group in dimension {#syntax#}dimension{#endsyntax#}. This function returns values between {#syntax#}0{#endsyntax#} (inclusive) and {#syntax#}@workGroupSize(dimension){#endsyntax#} (exclusive). 5867 </p> 5868 {#header_close#} 5869 5870 {#header_close#} 5871 5872 {#header_open|Build Mode#} 5873 <p> 5874 Zig has four build modes: 5875 </p> 5876 <ul> 5877 <li>{#link|Debug#} (default)</li> 5878 <li>{#link|ReleaseFast#}</li> 5879 <li>{#link|ReleaseSafe#}</li> 5880 <li>{#link|ReleaseSmall#}</li> 5881 </ul> 5882 <p> 5883 To add standard build options to a <code class="file">build.zig</code> file: 5884 </p> 5885 {#code|build.zig#} 5886 5887 <p> 5888 This causes these options to be available: 5889 </p> 5890 <dl> 5891 <dt><kbd>-Doptimize=Debug</kbd></dt><dd>Optimizations off and safety on (default)</dd> 5892 <dt><kbd>-Doptimize=ReleaseSafe</kbd></dt><dd>Optimizations on and safety on</dd> 5893 <dt><kbd>-Doptimize=ReleaseFast</kbd></dt><dd>Optimizations on and safety off</dd> 5894 <dt><kbd>-Doptimize=ReleaseSmall</kbd></dt><dd>Size optimizations on and safety off</dd> 5895 </dl> 5896 {#header_open|Debug#} 5897 {#shell_samp#}$ zig build-exe example.zig{#end_shell_samp#} 5898 <ul> 5899 <li>Fast compilation speed</li> 5900 <li>Safety checks enabled</li> 5901 <li>Slow runtime performance</li> 5902 <li>Large binary size</li> 5903 <li>No reproducible build requirement</li> 5904 </ul> 5905 {#header_close#} 5906 {#header_open|ReleaseFast#} 5907 {#shell_samp#}$ zig build-exe example.zig -O ReleaseFast{#end_shell_samp#} 5908 <ul> 5909 <li>Fast runtime performance</li> 5910 <li>Safety checks disabled</li> 5911 <li>Slow compilation speed</li> 5912 <li>Large binary size</li> 5913 <li>Reproducible build</li> 5914 </ul> 5915 {#header_close#} 5916 {#header_open|ReleaseSafe#} 5917 {#shell_samp#}$ zig build-exe example.zig -O ReleaseSafe{#end_shell_samp#} 5918 <ul> 5919 <li>Medium runtime performance</li> 5920 <li>Safety checks enabled</li> 5921 <li>Slow compilation speed</li> 5922 <li>Large binary size</li> 5923 <li>Reproducible build</li> 5924 </ul> 5925 {#header_close#} 5926 {#header_open|ReleaseSmall#} 5927 {#shell_samp#}$ zig build-exe example.zig -O ReleaseSmall{#end_shell_samp#} 5928 <ul> 5929 <li>Medium runtime performance</li> 5930 <li>Safety checks disabled</li> 5931 <li>Slow compilation speed</li> 5932 <li>Small binary size</li> 5933 <li>Reproducible build</li> 5934 </ul> 5935 {#header_close#} 5936 {#see_also|Compile Variables|Zig Build System|Illegal Behavior#} 5937 {#header_close#} 5938 5939 {#header_open|Single Threaded Builds#} 5940 <p>Zig has a compile option <kbd>-fsingle-threaded</kbd> which has the following effects:</p> 5941 <ul> 5942 <li>All {#link|Thread Local Variables#} are treated as regular {#link|Container Level Variables#}.</li> 5943 <li>The overhead of {#link|Async Functions#} becomes equivalent to function call overhead.</li> 5944 <li>The {#syntax#}@import("builtin").single_threaded{#endsyntax#} becomes {#syntax#}true{#endsyntax#} 5945 and therefore various userland APIs which read this variable become more efficient. 5946 For example {#syntax#}std.Mutex{#endsyntax#} becomes 5947 an empty data structure and all of its functions become no-ops.</li> 5948 </ul> 5949 {#header_close#} 5950 5951 {#header_open|Illegal Behavior#} 5952 <p> 5953 Many operations in Zig trigger what is known as "Illegal Behavior" (IB). If Illegal Behavior is detected at 5954 compile-time, Zig emits a compile error and refuses to continue. Otherwise, when Illegal Behavior is not caught 5955 at compile-time, it falls into one of two categories. 5956 </p> 5957 <p> 5958 Some Illegal Behavior is <em>safety-checked</em>: this means that the compiler will insert "safety checks" 5959 anywhere that the Illegal Behavior may occur at runtime, to determine whether it is about to happen. If it 5960 is, the safety check "fails", which triggers a panic. 5961 </p> 5962 <p> 5963 All other Illegal Behavior is <em>unchecked</em>, meaning the compiler is unable to insert safety checks for 5964 it. If Unchecked Illegal Behavior is invoked at runtime, anything can happen: usually that will be some kind of 5965 crash, but the optimizer is free to make Unchecked Illegal Behavior do anything, such as calling arbitrary functions 5966 or clobbering arbitrary data. This is similar to the concept of "undefined behavior" in some other languages. Note that 5967 Unchecked Illegal Behavior still always results in a compile error if evaluated at {#link|comptime#}, because the Zig 5968 compiler is able to perform more sophisticated checks at compile-time than at runtime. 5969 </p> 5970 <p> 5971 Most Illegal Behavior is safety-checked. However, to facilitate optimizations, safety checks are disabled by default 5972 in the {#link|ReleaseFast#} and {#link|ReleaseSmall#} optimization modes. Safety checks can also be enabled or disabled 5973 on a per-block basis, overriding the default for the current optimization mode, using {#link|@setRuntimeSafety#}. When 5974 safety checks are disabled, Safety-Checked Illegal Behavior behaves like Unchecked Illegal Behavior; that is, any behavior 5975 may result from invoking it. 5976 </p> 5977 <p> 5978 When a safety check fails, Zig's default panic handler crashes with a stack trace, like this: 5979 </p> 5980 {#code|test_illegal_behavior.zig#} 5981 5982 {#header_open|Reaching Unreachable Code#} 5983 <p>At compile-time:</p> 5984 {#code|test_comptime_reaching_unreachable.zig#} 5985 5986 <p>At runtime:</p> 5987 {#code|runtime_reaching_unreachable.zig#} 5988 5989 {#header_close#} 5990 {#header_open|Index out of Bounds#} 5991 <p>At compile-time:</p> 5992 {#code|test_comptime_index_out_of_bounds.zig#} 5993 5994 <p>At runtime:</p> 5995 {#code|runtime_index_out_of_bounds.zig#} 5996 5997 {#header_close#} 5998 {#header_open|Cast Negative Number to Unsigned Integer#} 5999 <p>At compile-time:</p> 6000 {#code|test_comptime_invalid_cast.zig#} 6001 6002 <p>At runtime:</p> 6003 {#code|runtime_invalid_cast.zig#} 6004 6005 <p> 6006 To obtain the maximum value of an unsigned integer, use {#syntax#}std.math.maxInt{#endsyntax#}. 6007 </p> 6008 {#header_close#} 6009 {#header_open|Cast Truncates Data#} 6010 <p>At compile-time:</p> 6011 {#code|test_comptime_invalid_cast_truncate.zig#} 6012 6013 <p>At runtime:</p> 6014 {#code|runtime_invalid_cast_truncate.zig#} 6015 6016 <p> 6017 To truncate bits, use {#link|@truncate#}. 6018 </p> 6019 {#header_close#} 6020 {#header_open|Integer Overflow#} 6021 {#header_open|Default Operations#} 6022 <p>The following operators can cause integer overflow:</p> 6023 <ul> 6024 <li>{#syntax#}+{#endsyntax#} (addition)</li> 6025 <li>{#syntax#}-{#endsyntax#} (subtraction)</li> 6026 <li>{#syntax#}-{#endsyntax#} (negation)</li> 6027 <li>{#syntax#}*{#endsyntax#} (multiplication)</li> 6028 <li>{#syntax#}/{#endsyntax#} (division)</li> 6029 <li>{#link|@divTrunc#} (division)</li> 6030 <li>{#link|@divFloor#} (division)</li> 6031 <li>{#link|@divExact#} (division)</li> 6032 </ul> 6033 <p>Example with addition at compile-time:</p> 6034 {#code|test_comptime_overflow.zig#} 6035 6036 <p>At runtime:</p> 6037 {#code|runtime_overflow.zig#} 6038 6039 {#header_close#} 6040 {#header_open|Standard Library Math Functions#} 6041 <p>These functions provided by the standard library return possible errors.</p> 6042 <ul> 6043 <li>{#syntax#}@import("std").math.add{#endsyntax#}</li> 6044 <li>{#syntax#}@import("std").math.sub{#endsyntax#}</li> 6045 <li>{#syntax#}@import("std").math.mul{#endsyntax#}</li> 6046 <li>{#syntax#}@import("std").math.divTrunc{#endsyntax#}</li> 6047 <li>{#syntax#}@import("std").math.divFloor{#endsyntax#}</li> 6048 <li>{#syntax#}@import("std").math.divExact{#endsyntax#}</li> 6049 <li>{#syntax#}@import("std").math.shl{#endsyntax#}</li> 6050 </ul> 6051 <p>Example of catching an overflow for addition:</p> 6052 {#code|math_add.zig#} 6053 6054 {#header_close#} 6055 {#header_open|Builtin Overflow Functions#} 6056 <p> 6057 These builtins return a tuple containing whether there was an overflow 6058 (as a {#syntax#}u1{#endsyntax#}) and the possibly overflowed bits of the operation: 6059 </p> 6060 <ul> 6061 <li>{#link|@addWithOverflow#}</li> 6062 <li>{#link|@subWithOverflow#}</li> 6063 <li>{#link|@mulWithOverflow#}</li> 6064 <li>{#link|@shlWithOverflow#}</li> 6065 </ul> 6066 <p> 6067 Example of {#link|@addWithOverflow#}: 6068 </p> 6069 {#code|addWithOverflow_builtin.zig#} 6070 6071 {#header_close#} 6072 {#header_open|Wrapping Operations#} 6073 <p> 6074 These operations have guaranteed wraparound semantics. 6075 </p> 6076 <ul> 6077 <li>{#syntax#}+%{#endsyntax#} (wraparound addition)</li> 6078 <li>{#syntax#}-%{#endsyntax#} (wraparound subtraction)</li> 6079 <li>{#syntax#}-%{#endsyntax#} (wraparound negation)</li> 6080 <li>{#syntax#}*%{#endsyntax#} (wraparound multiplication)</li> 6081 </ul> 6082 {#code|test_wraparound_semantics.zig#} 6083 6084 {#header_close#} 6085 {#header_close#} 6086 {#header_open|Exact Left Shift Overflow#} 6087 <p>At compile-time:</p> 6088 {#code|test_comptime_shlExact_overflow.zig#} 6089 6090 <p>At runtime:</p> 6091 {#code|runtime_shlExact_overflow.zig#} 6092 6093 {#header_close#} 6094 {#header_open|Exact Right Shift Overflow#} 6095 <p>At compile-time:</p> 6096 {#code|test_comptime_shrExact_overflow.zig#} 6097 6098 <p>At runtime:</p> 6099 {#code|runtime_shrExact_overflow.zig#} 6100 6101 {#header_close#} 6102 {#header_open|Division by Zero#} 6103 <p>At compile-time:</p> 6104 {#code|test_comptime_division_by_zero.zig#} 6105 6106 <p>At runtime:</p> 6107 {#code|runtime_division_by_zero.zig#} 6108 6109 {#header_close#} 6110 {#header_open|Remainder Division by Zero#} 6111 <p>At compile-time:</p> 6112 {#code|test_comptime_remainder_division_by_zero.zig#} 6113 6114 <p>At runtime:</p> 6115 {#code|runtime_remainder_division_by_zero.zig#} 6116 6117 {#header_close#} 6118 {#header_open|Exact Division Remainder#} 6119 <p>At compile-time:</p> 6120 {#code|test_comptime_divExact_remainder.zig#} 6121 6122 <p>At runtime:</p> 6123 {#code|runtime_divExact_remainder.zig#} 6124 6125 {#header_close#} 6126 {#header_open|Attempt to Unwrap Null#} 6127 <p>At compile-time:</p> 6128 {#code|test_comptime_unwrap_null.zig#} 6129 6130 <p>At runtime:</p> 6131 {#code|runtime_unwrap_null.zig#} 6132 6133 <p>One way to avoid this crash is to test for null instead of assuming non-null, with 6134 the {#syntax#}if{#endsyntax#} expression:</p> 6135 {#code|testing_null_with_if.zig#} 6136 6137 {#see_also|Optionals#} 6138 {#header_close#} 6139 {#header_open|Attempt to Unwrap Error#} 6140 <p>At compile-time:</p> 6141 {#code|test_comptime_unwrap_error.zig#} 6142 6143 <p>At runtime:</p> 6144 {#code|runtime_unwrap_error.zig#} 6145 6146 <p>One way to avoid this crash is to test for an error instead of assuming a successful result, with 6147 the {#syntax#}if{#endsyntax#} expression:</p> 6148 {#code|testing_error_with_if.zig#} 6149 6150 {#see_also|Errors#} 6151 {#header_close#} 6152 {#header_open|Invalid Error Code#} 6153 <p>At compile-time:</p> 6154 {#code|test_comptime_invalid_error_code.zig#} 6155 6156 <p>At runtime:</p> 6157 {#code|runtime_invalid_error_code.zig#} 6158 6159 {#header_close#} 6160 {#header_open|Invalid Enum Cast#} 6161 <p>At compile-time:</p> 6162 {#code|test_comptime_invalid_enum_cast.zig#} 6163 6164 <p>At runtime:</p> 6165 {#code|runtime_invalid_enum_cast.zig#} 6166 6167 {#header_close#} 6168 6169 {#header_open|Invalid Error Set Cast#} 6170 <p>At compile-time:</p> 6171 {#code|test_comptime_invalid_error_set_cast.zig#} 6172 6173 <p>At runtime:</p> 6174 {#code|runtime_invalid_error_set_cast.zig#} 6175 6176 {#header_close#} 6177 6178 {#header_open|Incorrect Pointer Alignment#} 6179 <p>At compile-time:</p> 6180 {#code|test_comptime_incorrect_pointer_alignment.zig#} 6181 6182 <p>At runtime:</p> 6183 {#code|runtime_incorrect_pointer_alignment.zig#} 6184 6185 {#header_close#} 6186 {#header_open|Wrong Union Field Access#} 6187 <p>At compile-time:</p> 6188 {#code|test_comptime_wrong_union_field_access.zig#} 6189 6190 <p>At runtime:</p> 6191 {#code|runtime_wrong_union_field_access.zig#} 6192 6193 <p> 6194 This safety is not available for {#syntax#}extern{#endsyntax#} or {#syntax#}packed{#endsyntax#} unions. 6195 </p> 6196 <p> 6197 To change the active field of a union, assign the entire union, like this: 6198 </p> 6199 {#code|change_active_union_field.zig#} 6200 6201 <p> 6202 To change the active field of a union when a meaningful value for the field is not known, 6203 use {#link|undefined#}, like this: 6204 </p> 6205 {#code|undefined_active_union_field.zig#} 6206 6207 {#see_also|union|extern union#} 6208 {#header_close#} 6209 6210 {#header_open|Out of Bounds Float to Integer Cast#} 6211 <p> 6212 This happens when casting a float to an integer where the float has a value outside the 6213 integer type's range. 6214 </p> 6215 <p>At compile-time:</p> 6216 {#code|test_comptime_out_of_bounds_float_to_integer_cast.zig#} 6217 6218 <p>At runtime:</p> 6219 {#code|runtime_out_of_bounds_float_to_integer_cast.zig#} 6220 6221 {#header_close#} 6222 6223 {#header_open|Pointer Cast Invalid Null#} 6224 <p> 6225 This happens when casting a pointer with the address 0 to a pointer which may not have the address 0. 6226 For example, {#link|C Pointers#}, {#link|Optional Pointers#}, and {#link|allowzero#} pointers 6227 allow address zero, but normal {#link|Pointers#} do not. 6228 </p> 6229 <p>At compile-time:</p> 6230 {#code|test_comptime_invalid_null_pointer_cast.zig#} 6231 6232 <p>At runtime:</p> 6233 {#code|runtime_invalid_null_pointer_cast.zig#} 6234 6235 {#header_close#} 6236 6237 {#header_close#} 6238 {#header_open|Memory#} 6239 <p> 6240 The Zig language performs no memory management on behalf of the programmer. This is 6241 why Zig has no runtime, and why Zig code works seamlessly in so many environments, 6242 including real-time software, operating system kernels, embedded devices, and 6243 low latency servers. As a consequence, Zig programmers must always be able to answer 6244 the question: 6245 </p> 6246 <p>{#link|Where are the bytes?#}</p> 6247 <p> 6248 Like Zig, the C programming language has manual memory management. However, unlike Zig, 6249 C has a default allocator - <code>malloc</code>, <code>realloc</code>, and <code>free</code>. 6250 When linking against libc, Zig exposes this allocator with {#syntax#}std.heap.c_allocator{#endsyntax#}. 6251 However, by convention, there is no default allocator in Zig. Instead, functions which need to 6252 allocate accept an {#syntax#}Allocator{#endsyntax#} parameter. Likewise, some data structures 6253 accept an {#syntax#}Allocator{#endsyntax#} parameter in their initialization functions: 6254 </p> 6255 {#code|test_allocator.zig#} 6256 6257 <p> 6258 In the above example, 100 bytes of stack memory are used to initialize a 6259 {#syntax#}FixedBufferAllocator{#endsyntax#}, which is then passed to a function. 6260 As a convenience there is a global {#syntax#}FixedBufferAllocator{#endsyntax#} 6261 available for quick tests at {#syntax#}std.testing.allocator{#endsyntax#}, 6262 which will also perform basic leak detection. 6263 </p> 6264 <p> 6265 Zig has a general purpose allocator available to be imported 6266 with {#syntax#}std.heap.GeneralPurposeAllocator{#endsyntax#}. However, it is still recommended to 6267 follow the {#link|Choosing an Allocator#} guide. 6268 </p> 6269 6270 {#header_open|Choosing an Allocator#} 6271 <p>What allocator to use depends on a number of factors. Here is a flow chart to help you decide: 6272 </p> 6273 <ol> 6274 <li> 6275 Are you making a library? In this case, best to accept an {#syntax#}Allocator{#endsyntax#} 6276 as a parameter and allow your library's users to decide what allocator to use. 6277 </li> 6278 <li>Are you linking libc? In this case, {#syntax#}std.heap.c_allocator{#endsyntax#} is likely 6279 the right choice, at least for your main allocator.</li> 6280 <li> 6281 Is the maximum number of bytes that you will need bounded by a number known at 6282 {#link|comptime#}? In this case, use {#syntax#}std.heap.FixedBufferAllocator{#endsyntax#}. 6283 </li> 6284 <li> 6285 Is your program a command line application which runs from start to end without any fundamental 6286 cyclical pattern (such as a video game main loop, or a web server request handler), 6287 such that it would make sense to free everything at once at the end? 6288 In this case, it is recommended to follow this pattern: 6289 {#code|cli_allocation.zig#} 6290 6291 When using this kind of allocator, there is no need to free anything manually. Everything 6292 gets freed at once with the call to {#syntax#}arena.deinit(){#endsyntax#}. 6293 </li> 6294 <li> 6295 Are the allocations part of a cyclical pattern such as a video game main loop, or a web 6296 server request handler? If the allocations can all be freed at once, at the end of the cycle, 6297 for example once the video game frame has been fully rendered, or the web server request has 6298 been served, then {#syntax#}std.heap.ArenaAllocator{#endsyntax#} is a great candidate. As 6299 demonstrated in the previous bullet point, this allows you to free entire arenas at once. 6300 Note also that if an upper bound of memory can be established, then 6301 {#syntax#}std.heap.FixedBufferAllocator{#endsyntax#} can be used as a further optimization. 6302 </li> 6303 <li> 6304 Are you writing a test, and you want to make sure {#syntax#}error.OutOfMemory{#endsyntax#} 6305 is handled correctly? In this case, use {#syntax#}std.testing.FailingAllocator{#endsyntax#}. 6306 </li> 6307 <li> 6308 Are you writing a test? In this case, use {#syntax#}std.testing.allocator{#endsyntax#}. 6309 </li> 6310 <li> 6311 Finally, if none of the above apply, you need a general purpose allocator. 6312 If you are in Debug mode, {#syntax#}std.heap.DebugAllocator{#endsyntax#} is available as a 6313 function that takes a {#link|comptime#} {#link|struct#} of configuration options and returns a type. 6314 Generally, you will set up exactly one in your main function, and 6315 then pass it or sub-allocators around to various parts of your 6316 application. 6317 </li> 6318 <li> 6319 If you are compiling in ReleaseFast mode, {#syntax#}std.heap.smp_allocator{#endsyntax#} is 6320 a solid choice for a general purpose allocator. 6321 </li> 6322 <li> 6323 You can also consider implementing an allocator. 6324 </li> 6325 </ol> 6326 {#header_close#} 6327 6328 {#header_open|Where are the bytes?#} 6329 <p>String literals such as {#syntax#}"hello"{#endsyntax#} are in the global constant data section. 6330 This is why it is an error to pass a string literal to a mutable slice, like this: 6331 </p> 6332 {#code|test_string_literal_to_slice.zig#} 6333 6334 <p>However if you make the slice constant, then it works:</p> 6335 {#code|test_string_literal_to_const_slice.zig#} 6336 6337 <p> 6338 Just like string literals, {#syntax#}const{#endsyntax#} declarations, when the value is known at {#link|comptime#}, 6339 are stored in the global constant data section. Also {#link|Compile Time Variables#} are stored 6340 in the global constant data section. 6341 </p> 6342 <p> 6343 {#syntax#}var{#endsyntax#} declarations inside functions are stored in the function's stack frame. Once a function returns, 6344 any {#link|Pointers#} to variables in the function's stack frame become invalid references, and 6345 dereferencing them becomes unchecked {#link|Illegal Behavior#}. 6346 </p> 6347 <p> 6348 {#syntax#}var{#endsyntax#} declarations at the top level or in {#link|struct#} declarations are stored in the global 6349 data section. 6350 </p> 6351 <p> 6352 The location of memory allocated with {#syntax#}allocator.alloc{#endsyntax#} or 6353 {#syntax#}allocator.create{#endsyntax#} is determined by the allocator's implementation. 6354 </p> 6355 <p>TODO: thread local variables</p> 6356 {#header_close#} 6357 6358 {#header_open|Heap Allocation Failure#} 6359 <p> 6360 Many programming languages choose to handle the possibility of heap allocation failure by 6361 unconditionally crashing. By convention, Zig programmers do not consider this to be a 6362 satisfactory solution. Instead, {#syntax#}error.OutOfMemory{#endsyntax#} represents 6363 heap allocation failure, and Zig libraries return this error code whenever heap allocation 6364 failure prevented an operation from completing successfully. 6365 </p> 6366 <p> 6367 Some have argued that because some operating systems such as Linux have memory overcommit enabled by 6368 default, it is pointless to handle heap allocation failure. There are many problems with this reasoning: 6369 </p> 6370 <ul> 6371 <li>Only some operating systems have an overcommit feature. 6372 <ul> 6373 <li>Linux has it enabled by default, but it is configurable.</li> 6374 <li>Windows does not overcommit.</li> 6375 <li>Embedded systems do not have overcommit.</li> 6376 <li>Hobby operating systems may or may not have overcommit.</li> 6377 </ul> 6378 </li> 6379 <li> 6380 For real-time systems, not only is there no overcommit, but typically the maximum amount 6381 of memory per application is determined ahead of time. 6382 </li> 6383 <li> 6384 When writing a library, one of the main goals is code reuse. By making code handle 6385 allocation failure correctly, a library becomes eligible to be reused in 6386 more contexts. 6387 </li> 6388 <li> 6389 Although some software has grown to depend on overcommit being enabled, its existence 6390 is the source of countless user experience disasters. When a system with overcommit enabled, 6391 such as Linux on default settings, comes close to memory exhaustion, the system locks up 6392 and becomes unusable. At this point, the OOM Killer selects an application to kill 6393 based on heuristics. This non-deterministic decision often results in an important process 6394 being killed, and often fails to return the system back to working order. 6395 </li> 6396 </ul> 6397 {#header_close#} 6398 6399 {#header_open|Recursion#} 6400 <p> 6401 Recursion is a fundamental tool in modeling software. However it has an often-overlooked problem: 6402 unbounded memory allocation. 6403 </p> 6404 <p> 6405 Recursion is an area of active experimentation in Zig and so the documentation here is not final. 6406 You can read a 6407 <a href="https://ziglang.org/download/0.3.0/release-notes.html#recursion">summary of recursion status in the 0.3.0 release notes</a>. 6408 </p> 6409 <p> 6410 The short summary is that currently recursion works normally as you would expect. Although Zig code 6411 is not yet protected from stack overflow, it is planned that a future version of Zig will provide 6412 such protection, with some degree of cooperation from Zig code required. 6413 </p> 6414 {#header_close#} 6415 6416 {#header_open|Lifetime and Ownership#} 6417 <p> 6418 It is the Zig programmer's responsibility to ensure that a {#link|pointer|Pointers#} is not 6419 accessed when the memory pointed to is no longer available. Note that a {#link|slice|Slices#} 6420 is a form of pointer, in that it references other memory. 6421 </p> 6422 <p> 6423 In order to prevent bugs, there are some helpful conventions to follow when dealing with pointers. 6424 In general, when a function returns a pointer, the documentation for the function should explain 6425 who "owns" the pointer. This concept helps the programmer decide when it is appropriate, if ever, 6426 to free the pointer. 6427 </p> 6428 <p> 6429 For example, the function's documentation may say "caller owns the returned memory", in which case 6430 the code that calls the function must have a plan for when to free that memory. Probably in this situation, 6431 the function will accept an {#syntax#}Allocator{#endsyntax#} parameter. 6432 </p> 6433 <p> 6434 Sometimes the lifetime of a pointer may be more complicated. For example, the 6435 {#syntax#}std.ArrayList(T).items{#endsyntax#} slice has a lifetime that remains 6436 valid until the next time the list is resized, such as by appending new elements. 6437 </p> 6438 <p> 6439 The API documentation for functions and data structures should take great care to explain 6440 the ownership and lifetime semantics of pointers. Ownership determines whose responsibility it 6441 is to free the memory referenced by the pointer, and lifetime determines the point at which 6442 the memory becomes inaccessible (lest {#link|Illegal Behavior#} occur). 6443 </p> 6444 {#header_close#} 6445 6446 {#header_close#} 6447 {#header_open|Compile Variables#} 6448 <p> 6449 Compile variables are accessible by importing the {#syntax#}"builtin"{#endsyntax#} package, 6450 which the compiler makes available to every Zig source file. It contains 6451 compile-time constants such as the current target, endianness, and release mode. 6452 </p> 6453 {#code|compile_variables.zig#} 6454 6455 <p> 6456 Example of what is imported with {#syntax#}@import("builtin"){#endsyntax#}: 6457 </p> 6458 {#builtin#} 6459 {#see_also|Build Mode#} 6460 {#header_close#} 6461 {#header_open|Compilation Model#} 6462 <p> 6463 A Zig compilation is separated into <em>modules</em>. Each module is a collection of Zig source files, 6464 one of which is the module's <em>root source file</em>. Each module can <em>depend</em> on any number of 6465 other modules, forming a directed graph (dependency loops between modules are allowed). If module A 6466 depends on module B, then any Zig source file in module A can import the <em>root source file</em> of 6467 module B using {#syntax#}@import{#endsyntax#} with the module's name. In essence, a module acts as an 6468 alias to import a Zig source file (which might exist in a completely separate part of the filesystem). 6469 </p> 6470 <p> 6471 A simple Zig program compiled with <code>zig build-exe</code> has two key modules: the one containing your 6472 code, known as the "main" or "root" module, and the standard library. Your module <em>depends on</em> 6473 the standard library module under the name "std", which is what allows you to write 6474 {#syntax#}@import("std"){#endsyntax#}! In fact, every single module in a Zig compilation — including 6475 the standard library itself — implicitly depends on the standard library module under the name "std". 6476 </p> 6477 <p> 6478 The "root module" (the one provided by you in the <code>zig build-exe</code> example) has a special 6479 property. Like the standard library, it is implicitly made available to all modules (including itself), 6480 this time under the name "root". So, {#syntax#}@import("root"){#endsyntax#} will always be equivalent to 6481 {#syntax#}@import{#endsyntax#} of your "main" source file (often, but not necessarily, named 6482 <code>main.zig</code>). 6483 </p> 6484 {#header_open|Source File Structs#} 6485 <p> 6486 Every Zig source file is implicitly a {#syntax#}struct{#endsyntax#} declaration; you can imagine that 6487 the file's contents are literally surrounded by {#syntax#}struct { ... }{#endsyntax#}. This means that 6488 as well as declarations, the top level of a file is permitted to contain fields: 6489 </p> 6490 {#code|TopLevelFields.zig#} 6491 <p> 6492 Such files can be instantiated just like any other {#syntax#}struct{#endsyntax#} type. A file's "root 6493 struct type" can be referred to within that file using {#link|@This#}. 6494 </p> 6495 {#header_close#} 6496 {#header_open|File and Declaration Discovery#} 6497 <p> 6498 Zig places importance on the concept of whether any piece of code is <em>semantically analyzed</em>; in 6499 essence, whether the compiler "looks at" it. What code is analyzed is based on what files and 6500 declarations are "discovered" from a certain point. This process of "discovery" is based on a simple set 6501 of recursive rules: 6502 </p> 6503 <ul> 6504 <li>If a call to {#syntax#}@import{#endsyntax#} is analyzed, the file being imported is analyzed.</li> 6505 <li>If a type (including a file) is analyzed, all {#syntax#}comptime{#endsyntax#} and {#syntax#}export{#endsyntax#} declarations within it are analyzed.</li> 6506 <li>If a type (including a file) is analyzed, and the compilation is for a {#link|test|Zig Test#}, and the module the type is within is the root module of the compilation, then all {#syntax#}test{#endsyntax#} declarations within it are also analyzed.</li> 6507 <li>If a reference to a named declaration (i.e. a usage of it) is analyzed, the declaration being referenced is analyzed. Declarations are order-independent, so this reference may be above or below the declaration being referenced, or even in another file entirely.</li> 6508 </ul> 6509 <p> 6510 That's it! Those rules define how Zig files and declarations are discovered. All that remains is to 6511 understand where this process <em>starts</em>. 6512 </p> 6513 <p> 6514 The answer to that is the root of the standard library: every Zig compilation begins by analyzing the 6515 file <code>lib/std/std.zig</code>. This file contains a {#syntax#}comptime{#endsyntax#} declaration 6516 which imports {#syntax#}lib/std/start.zig{#endsyntax#}, and that file in turn uses 6517 {#syntax#}@import("root"){#endsyntax#} to reference the "root module"; so, the file you provide as your 6518 main module's root source file is effectively also a root, because the standard library will always 6519 reference it. 6520 </p> 6521 <p> 6522 It is often desirable to make sure that certain declarations — particularly {#syntax#}test{#endsyntax#} 6523 or {#syntax#}export{#endsyntax#} declarations — are discovered. Based on the above rules, a common 6524 strategy for this is to use {#syntax#}@import{#endsyntax#} within a {#syntax#}comptime{#endsyntax#} or 6525 {#syntax#}test{#endsyntax#} block: 6526 </p> 6527 {#syntax_block|zig|force_file_discovery.zig#} 6528 comptime { 6529 // This will ensure that the file 'api.zig' is always discovered (as long as this file is discovered). 6530 // It is useful if 'api.zig' contains important exported declarations. 6531 _ = @import("api.zig"); 6532 6533 // We could also have a file which contains declarations we only want to export depending on a comptime 6534 // condition. In that case, we can use an `if` statement here: 6535 if (builtin.os.tag == .windows) { 6536 _ = @import("windows_api.zig"); 6537 } 6538 } 6539 6540 test { 6541 // This will ensure that the file 'tests.zig' is always discovered (as long as this file is discovered), 6542 // if this compilation is a test. It is useful if 'tests.zig' contains tests we want to ensure are run. 6543 _ = @import("tests.zig"); 6544 6545 // We could also have a file which contains tests we only want to run depending on a comptime condition. 6546 // In that case, we can use an `if` statement here: 6547 if (builtin.os.tag == .windows) { 6548 _ = @import("windows_tests.zig"); 6549 } 6550 } 6551 6552 const builtin = @import("builtin"); 6553 {#end_syntax_block#} 6554 {#header_close#} 6555 {#header_open|Special Root Declarations#} 6556 <p> 6557 Because the root module's root source file is always accessible using 6558 {#syntax#}@import("root"){#endsyntax#}, is is sometimes used by libraries — including the Zig Standard 6559 Library — as a place for the program to expose some "global" information to that library. The Zig 6560 Standard Library will look for several declarations in this file. 6561 </p> 6562 {#header_open|Entry Point#} 6563 <p> 6564 When building an executable, the most important thing to be looked up in this file is the program's 6565 <em>entry point</em>. Most commonly, this is a function named {#syntax#}main{#endsyntax#}, which 6566 {#syntax#}std.start{#endsyntax#} will call just after performing important initialization work. 6567 </p> 6568 <p> 6569 Alternatively, the presence of a declaration named {#syntax#}_start{#endsyntax#} (for instance, 6570 {#syntax#}pub const _start = {};{#endsyntax#}) will disable the default {#syntax#}std.start{#endsyntax#} 6571 logic, allowing your root source file to export a low-level entry point as needed. 6572 </p> 6573 {#code|entry_point.zig#} 6574 <p> 6575 If the Zig compilation links libc, the {#syntax#}main{#endsyntax#} function can optionally be an 6576 {#syntax#}export fn{#endsyntax#} which matches the signature of the C <code>main</code> function: 6577 </p> 6578 {#code|libc_export_entry_point.zig#} 6579 <p> 6580 {#syntax#}std.start{#endsyntax#} may also use other entry point declarations in certain situations, such 6581 as {#syntax#}wWinMain{#endsyntax#} or {#syntax#}EfiMain{#endsyntax#}. Refer to the 6582 {#syntax#}lib/std/start.zig{#endsyntax#} logic for details of these declarations. 6583 </p> 6584 {#header_close#} 6585 {#header_open|Standard Library Options#} 6586 <p> 6587 The standard library also looks for a declaration in the root module's root source file named 6588 {#syntax#}std_options{#endsyntax#}. If present, this declaration is expected to be a struct of type 6589 {#syntax#}std.Options{#endsyntax#}, and allows the program to customize some standard library 6590 functionality, such as the {#syntax#}std.log{#endsyntax#} implementation. 6591 </p> 6592 {#code|std_options.zig#} 6593 {#header_close#} 6594 {#header_open|Panic Handler#} 6595 <p> 6596 The Zig Standard Library looks for a declaration named {#syntax#}panic{#endsyntax#} in the root module's 6597 root source file. If present, it is expected to be a namespace (container type) with declarations 6598 providing different panic handlers. 6599 </p> 6600 <p> 6601 See {#syntax#}std.debug.simple_panic{#endsyntax#} for a basic implementation of this namespace. 6602 </p> 6603 <p> 6604 Overriding how the panic handler actually outputs messages, but keeping the formatted safety panics 6605 which are enabled by default, can be easily achieved with {#syntax#}std.debug.FullPanic{#endsyntax#}: 6606 </p> 6607 {#code|panic_handler.zig#} 6608 {#header_close#} 6609 {#header_close#} 6610 {#header_close#} 6611 {#header_open|Zig Build System#} 6612 <p> 6613 The Zig Build System provides a cross-platform, dependency-free way to declare 6614 the logic required to build a project. With this system, the logic to build 6615 a project is written in a build.zig file, using the Zig Build System API to 6616 declare and configure build artifacts and other tasks. 6617 </p> 6618 <p> 6619 Some examples of tasks the build system can help with: 6620 </p> 6621 <ul> 6622 <li>Performing tasks in parallel and caching the results.</li> 6623 <li>Depending on other projects.</li> 6624 <li>Providing a package for other projects to depend on.</li> 6625 <li>Creating build artifacts by executing the Zig compiler. This includes 6626 building Zig source code as well as C and C++ source code.</li> 6627 <li>Capturing user-configured options and using those options to configure 6628 the build.</li> 6629 <li>Surfacing build configuration as {#link|comptime#} values by providing a 6630 file that can be {#link|imported|@import#} by Zig code.</li> 6631 <li>Caching build artifacts to avoid unnecessarily repeating steps.</li> 6632 <li>Executing build artifacts or system-installed tools.</li> 6633 <li>Running tests and verifying the output of executing a build artifact matches 6634 the expected value.</li> 6635 <li>Running <code>zig fmt</code> on a codebase or a subset of it.</li> 6636 <li>Custom tasks.</li> 6637 </ul> 6638 <p> 6639 To use the build system, run <kbd>zig build --help</kbd> 6640 to see a command-line usage help menu. This will include project-specific 6641 options that were declared in the build.zig script. 6642 </p> 6643 <p> 6644 For the time being, the build system documentation is hosted externally: 6645 <a href="https://ziglang.org/learn/build-system/">Build System Documentation</a> 6646 </p> 6647 {#header_close#} 6648 {#header_open|C#} 6649 <p> 6650 Although Zig is independent of C, and, unlike most other languages, does not depend on libc, 6651 Zig acknowledges the importance of interacting with existing C code. 6652 </p> 6653 <p> 6654 There are a few ways that Zig facilitates C interop. 6655 </p> 6656 {#header_open|C Type Primitives#} 6657 <p> 6658 These have guaranteed C ABI compatibility and can be used like any other type. 6659 </p> 6660 <ul> 6661 <li>{#syntax#}c_char{#endsyntax#}</li> 6662 <li>{#syntax#}c_short{#endsyntax#}</li> 6663 <li>{#syntax#}c_ushort{#endsyntax#}</li> 6664 <li>{#syntax#}c_int{#endsyntax#}</li> 6665 <li>{#syntax#}c_uint{#endsyntax#}</li> 6666 <li>{#syntax#}c_long{#endsyntax#}</li> 6667 <li>{#syntax#}c_ulong{#endsyntax#}</li> 6668 <li>{#syntax#}c_longlong{#endsyntax#}</li> 6669 <li>{#syntax#}c_ulonglong{#endsyntax#}</li> 6670 <li>{#syntax#}c_longdouble{#endsyntax#}</li> 6671 </ul> 6672 <p> 6673 To interop with the C {#syntax#}void{#endsyntax#} type, use {#syntax#}anyopaque{#endsyntax#}. 6674 </p> 6675 {#see_also|Primitive Types#} 6676 {#header_close#} 6677 {#header_open|Import from C Header File#} 6678 <p> 6679 The {#syntax#}@cImport{#endsyntax#} builtin function can be used 6680 to directly import symbols from <code class="file">.h</code> files: 6681 </p> 6682 {#code|cImport_builtin.zig#} 6683 6684 <p> 6685 The {#syntax#}@cImport{#endsyntax#} function takes an expression as a parameter. 6686 This expression is evaluated at compile-time and is used to control 6687 preprocessor directives and include multiple <code class="file">.h</code> files: 6688 </p> 6689 {#syntax_block|zig|@cImport Expression#} 6690 const builtin = @import("builtin"); 6691 6692 const c = @cImport({ 6693 @cDefine("NDEBUG", builtin.mode == .ReleaseFast); 6694 if (something) { 6695 @cDefine("_GNU_SOURCE", {}); 6696 } 6697 @cInclude("stdlib.h"); 6698 if (something) { 6699 @cUndef("_GNU_SOURCE"); 6700 } 6701 @cInclude("soundio.h"); 6702 }); 6703 {#end_syntax_block#} 6704 {#see_also|@cImport|@cInclude|@cDefine|@cUndef|@import#} 6705 {#header_close#} 6706 6707 {#header_open|C Translation CLI#} 6708 <p> 6709 Zig's C translation capability is available as a CLI tool via <kbd>zig translate-c</kbd>. 6710 It requires a single filename as an argument. It may also take a set of optional flags that are 6711 forwarded to clang. It writes the translated file to stdout. 6712 </p> 6713 {#header_open|Command line flags#} 6714 <ul> 6715 <li> 6716 <kbd>-I</kbd>: 6717 Specify a search directory for include files. May be used multiple times. Equivalent to 6718 <a href="https://releases.llvm.org/12.0.0/tools/clang/docs/ClangCommandLineReference.html#cmdoption-clang-i-dir"> 6719 clang's <kbd>-I</kbd> flag</a>. The current directory is <em>not</em> included by default; 6720 use <kbd>-I.</kbd> to include it. 6721 </li> 6722 <li> 6723 <kbd>-D</kbd>: Define a preprocessor macro. Equivalent to 6724 <a href="https://releases.llvm.org/12.0.0/tools/clang/docs/ClangCommandLineReference.html#cmdoption-clang-d-macro"> 6725 clang's <kbd>-D</kbd> flag</a>. 6726 </li> 6727 <li> 6728 <kbd>-cflags [flags] --</kbd>: Pass arbitrary additional 6729 <a href="https://releases.llvm.org/12.0.0/tools/clang/docs/ClangCommandLineReference.html">command line 6730 flags</a> to clang. Note: the list of flags must end with <kbd>--</kbd> 6731 </li> 6732 <li> 6733 <kbd>-target</kbd>: The {#link|target triple|Targets#} for the translated Zig code. 6734 If no target is specified, the current host target will be used. 6735 </li> 6736 </ul> 6737 {#header_close#} 6738 {#header_open|Using -target and -cflags#} 6739 <p> 6740 <strong>Important!</strong> When translating C code with <kbd>zig translate-c</kbd>, 6741 you <strong>must</strong> use the same <kbd>-target</kbd> triple that you will use when compiling 6742 the translated code. In addition, you <strong>must</strong> ensure that the <kbd>-cflags</kbd> used, 6743 if any, match the cflags used by code on the target system. Using the incorrect <kbd>-target</kbd> 6744 or <kbd>-cflags</kbd> could result in clang or Zig parse failures, or subtle ABI incompatibilities 6745 when linking with C code. 6746 </p> 6747 {#syntax_block|c|varytarget.h#} 6748 long FOO = __LONG_MAX__; 6749 {#end_syntax_block#} 6750 {#shell_samp#}$ zig translate-c -target thumb-freestanding-gnueabihf varytarget.h|grep FOO 6751 pub export var FOO: c_long = 2147483647; 6752 $ zig translate-c -target x86_64-macos-gnu varytarget.h|grep FOO 6753 pub export var FOO: c_long = 9223372036854775807;{#end_shell_samp#} 6754 {#syntax_block|c|varycflags.h#} 6755 enum FOO { BAR }; 6756 int do_something(enum FOO foo); 6757 {#end_syntax_block#} 6758 {#shell_samp#}$ zig translate-c varycflags.h|grep -B1 do_something 6759 pub const enum_FOO = c_uint; 6760 pub extern fn do_something(foo: enum_FOO) c_int; 6761 $ zig translate-c -cflags -fshort-enums -- varycflags.h|grep -B1 do_something 6762 pub const enum_FOO = u8; 6763 pub extern fn do_something(foo: enum_FOO) c_int;{#end_shell_samp#} 6764 {#header_close#} 6765 {#header_open|@cImport vs translate-c#} 6766 <p>{#syntax#}@cImport{#endsyntax#} and <kbd>zig translate-c</kbd> use the same underlying 6767 C translation functionality, so on a technical level they are equivalent. In practice, 6768 {#syntax#}@cImport{#endsyntax#} is useful as a way to quickly and easily access numeric constants, typedefs, 6769 and record types without needing any extra setup. If you need to pass {#link|cflags|Using -target and -cflags#} 6770 to clang, or if you would like to edit the translated code, it is recommended to use 6771 <kbd>zig translate-c</kbd> and save the results to a file. Common reasons for editing 6772 the generated code include: changing {#syntax#}anytype{#endsyntax#} parameters in function-like macros to more 6773 specific types; changing {#syntax#}[*c]T{#endsyntax#} pointers to {#syntax#}[*]T{#endsyntax#} or 6774 {#syntax#}*T{#endsyntax#} pointers for improved type safety; and 6775 {#link|enabling or disabling runtime safety|@setRuntimeSafety#} within specific functions. 6776 </p> 6777 {#header_close#} 6778 {#see_also|Targets|C Type Primitives|Pointers|C Pointers|Import from C Header File|@cInclude|@cImport|@setRuntimeSafety#} 6779 {#header_close#} 6780 {#header_open|C Translation Caching#} 6781 <p> 6782 The C translation feature (whether used via <kbd>zig translate-c</kbd> or 6783 {#syntax#}@cImport{#endsyntax#}) integrates with the Zig caching system. Subsequent runs with 6784 the same source file, target, and cflags will use the cache instead of repeatedly translating 6785 the same code. 6786 </p> 6787 <p> 6788 To see where the cached files are stored when compiling code that uses {#syntax#}@cImport{#endsyntax#}, 6789 use the <kbd>--verbose-cimport</kbd> flag: 6790 </p> 6791 {#code|verbose_cimport_flag.zig#} 6792 6793 <p> 6794 <code class="file">cimport.h</code> contains the file to translate (constructed from calls to 6795 {#syntax#}@cInclude{#endsyntax#}, {#syntax#}@cDefine{#endsyntax#}, and {#syntax#}@cUndef{#endsyntax#}), 6796 <code class="file">cimport.h.d</code> is the list of file dependencies, and 6797 <code class="file">cimport.zig</code> contains the translated output. 6798 </p> 6799 {#see_also|Import from C Header File|C Translation CLI|@cInclude|@cImport#} 6800 {#header_close#} 6801 {#header_open|Translation failures#} 6802 <p> 6803 Some C constructs cannot be translated to Zig - for example, <em>goto</em>, 6804 structs with bitfields, and token-pasting macros. Zig employs <em>demotion</em> to allow translation 6805 to continue in the face of non-translatable entities. 6806 </p> 6807 <p> 6808 Demotion comes in three varieties - {#link|opaque#}, <em>extern</em>, and 6809 {#syntax#}@compileError{#endsyntax#}. 6810 6811 C structs and unions that cannot be translated correctly will be translated as {#syntax#}opaque{}{#endsyntax#}. 6812 Functions that contain opaque types or code constructs that cannot be translated will be demoted 6813 to {#syntax#}extern{#endsyntax#} declarations. 6814 6815 Thus, non-translatable types can still be used as pointers, and non-translatable functions 6816 can be called so long as the linker is aware of the compiled function. 6817 </p> 6818 <p> 6819 {#syntax#}@compileError{#endsyntax#} is used when top-level definitions (global variables, 6820 function prototypes, macros) cannot be translated or demoted. Since Zig uses lazy analysis for 6821 top-level declarations, untranslatable entities will not cause a compile error in your code unless 6822 you actually use them. 6823 </p> 6824 {#see_also|opaque|extern|@compileError#} 6825 {#header_close#} 6826 {#header_open|C Macros#} 6827 <p> 6828 C Translation makes a best-effort attempt to translate function-like macros into equivalent 6829 Zig functions. Since C macros operate at the level of lexical tokens, not all C macros 6830 can be translated to Zig. Macros that cannot be translated will be demoted to 6831 {#syntax#}@compileError{#endsyntax#}. Note that C code which <em>uses</em> macros will be 6832 translated without any additional issues (since Zig operates on the pre-processed source 6833 with macros expanded). It is merely the macros themselves which may not be translatable to 6834 Zig. 6835 </p> 6836 <p>Consider the following example:</p> 6837 {#syntax_block|c|macro.c#} 6838 #define MAKELOCAL(NAME, INIT) int NAME = INIT 6839 int foo(void) { 6840 MAKELOCAL(a, 1); 6841 MAKELOCAL(b, 2); 6842 return a + b; 6843 } 6844 {#end_syntax_block#} 6845 {#shell_samp#}$ zig translate-c macro.c > macro.zig{#end_shell_samp#} 6846 {#code|macro.zig#} 6847 6848 <p>Note that {#syntax#}foo{#endsyntax#} was translated correctly despite using a non-translatable 6849 macro. {#syntax#}MAKELOCAL{#endsyntax#} was demoted to {#syntax#}@compileError{#endsyntax#} since 6850 it cannot be expressed as a Zig function; this simply means that you cannot directly use 6851 {#syntax#}MAKELOCAL{#endsyntax#} from Zig. 6852 </p> 6853 {#see_also|@compileError#} 6854 {#header_close#} 6855 6856 {#header_open|C Pointers#} 6857 <p> 6858 This type is to be avoided whenever possible. The only valid reason for using a C pointer is in 6859 auto-generated code from translating C code. 6860 </p> 6861 <p> 6862 When importing C header files, it is ambiguous whether pointers should be translated as 6863 single-item pointers ({#syntax#}*T{#endsyntax#}) or many-item pointers ({#syntax#}[*]T{#endsyntax#}). 6864 C pointers are a compromise so that Zig code can utilize translated header files directly. 6865 </p> 6866 <p>{#syntax#}[*c]T{#endsyntax#} - C pointer.</p> 6867 <ul> 6868 <li>Supports all the syntax of the other two pointer types ({#syntax#}*T{#endsyntax#}) and ({#syntax#}[*]T{#endsyntax#}).</li> 6869 <li>Coerces to other pointer types, as well as {#link|Optional Pointers#}. 6870 When a C pointer is coerced to a non-optional pointer, safety-checked 6871 {#link|Illegal Behavior#} occurs if the address is 0. 6872 </li> 6873 <li>Allows address 0. On non-freestanding targets, dereferencing address 0 is safety-checked 6874 {#link|Illegal Behavior#}. Optional C pointers introduce another bit to keep track of 6875 null, just like {#syntax#}?usize{#endsyntax#}. Note that creating an optional C pointer 6876 is unnecessary as one can use normal {#link|Optional Pointers#}. 6877 </li> 6878 <li>Supports {#link|Type Coercion#} to and from integers.</li> 6879 <li>Supports comparison with integers.</li> 6880 <li>Does not support Zig-only pointer attributes such as alignment. Use normal {#link|Pointers#} 6881 please!</li> 6882 </ul> 6883 <p>When a C pointer is pointing to a single struct (not an array), dereference the C pointer to 6884 access the struct's fields or member data. That syntax looks like 6885 this: </p> 6886 <p>{#syntax#}ptr_to_struct.*.struct_member{#endsyntax#}</p> 6887 <p>This is comparable to doing {#syntax#}->{#endsyntax#} in C.</p> 6888 <p> When a C pointer is pointing to an array of structs, the syntax reverts to this:</p> 6889 <p>{#syntax#}ptr_to_struct_array[index].struct_member{#endsyntax#}</p> 6890 {#header_close#} 6891 6892 {#header_open|C Variadic Functions#} 6893 <p>Zig supports extern variadic functions.</p> 6894 {#code|test_variadic_function.zig#} 6895 6896 <p> 6897 Variadic functions can be implemented using {#link|@cVaStart#}, {#link|@cVaEnd#}, {#link|@cVaArg#} and {#link|@cVaCopy#}. 6898 </p> 6899 {#code|test_defining_variadic_function.zig#} 6900 6901 {#header_close#} 6902 {#header_open|Exporting a C Library#} 6903 <p> 6904 One of the primary use cases for Zig is exporting a library with the C ABI for other programming languages 6905 to call into. The {#syntax#}export{#endsyntax#} keyword in front of functions, variables, and types causes them to 6906 be part of the library API: 6907 </p> 6908 {#code|mathtest.zig#} 6909 6910 <p>To make a static library:</p> 6911 {#shell_samp#}$ zig build-lib mathtest.zig{#end_shell_samp#} 6912 <p>To make a shared library:</p> 6913 {#shell_samp#}$ zig build-lib mathtest.zig -dynamic{#end_shell_samp#} 6914 <p>Here is an example with the {#link|Zig Build System#}:</p> 6915 {#syntax_block|c|test.c#} 6916 // This header is generated by zig from mathtest.zig 6917 #include "mathtest.h" 6918 #include <stdio.h> 6919 6920 int main(int argc, char **argv) { 6921 int32_t result = add(42, 1337); 6922 printf("%d\n", result); 6923 return 0; 6924 } 6925 {#end_syntax_block#} 6926 {#code|build_c.zig#} 6927 6928 {#shell_samp#}$ zig build test 6929 1379{#end_shell_samp#} 6930 {#see_also|export#} 6931 {#header_close#} 6932 {#header_open|Mixing Object Files#} 6933 <p> 6934 You can mix Zig object files with any other object files that respect the C ABI. Example: 6935 </p> 6936 {#code|base64.zig#} 6937 6938 {#syntax_block|c|test.c#} 6939 // This header is generated by zig from base64.zig 6940 #include "base64.h" 6941 6942 #include <string.h> 6943 #include <stdio.h> 6944 6945 int main(int argc, char **argv) { 6946 const char *encoded = "YWxsIHlvdXIgYmFzZSBhcmUgYmVsb25nIHRvIHVz"; 6947 char buf[200]; 6948 6949 size_t len = decode_base_64(buf, 200, encoded, strlen(encoded)); 6950 buf[len] = 0; 6951 puts(buf); 6952 6953 return 0; 6954 } 6955 {#end_syntax_block#} 6956 {#code|build_object.zig#} 6957 6958 {#shell_samp#}$ zig build 6959 $ ./zig-out/bin/test 6960 all your base are belong to us{#end_shell_samp#} 6961 {#see_also|Targets|Zig Build System#} 6962 {#header_close#} 6963 {#header_close#} 6964 {#header_open|WebAssembly#} 6965 <p>Zig supports building for WebAssembly out of the box.</p> 6966 {#header_open|Freestanding#} 6967 <p>For host environments like the web browser and nodejs, build as an executable using the freestanding 6968 OS target. Here's an example of running Zig code compiled to WebAssembly with nodejs.</p> 6969 {#code|math.zig#} 6970 6971 {#syntax_block|javascript|test.js#} 6972 const fs = require('fs'); 6973 const source = fs.readFileSync("./math.wasm"); 6974 const typedArray = new Uint8Array(source); 6975 6976 WebAssembly.instantiate(typedArray, { 6977 env: { 6978 print: (result) => { console.log(`The result is ${result}`); } 6979 }}).then(result => { 6980 const add = result.instance.exports.add; 6981 add(1, 2); 6982 }); 6983 {#end_syntax_block#} 6984 {#shell_samp#}$ node test.js 6985 The result is 3{#end_shell_samp#} 6986 {#header_close#} 6987 {#header_open|WASI#} 6988 <p>Zig's support for WebAssembly System Interface (WASI) is under active development. 6989 Example of using the standard library and reading command line arguments:</p> 6990 {#code|wasi_args.zig#} 6991 6992 {#shell_samp#}$ wasmtime wasi_args.wasm 123 hello 6993 0: wasi_args.wasm 6994 1: 123 6995 2: hello{#end_shell_samp#} 6996 <p>A more interesting example would be extracting the list of preopens from the runtime. 6997 This is now supported in the standard library via {#syntax#}std.fs.wasi.Preopens{#endsyntax#}:</p> 6998 {#code|wasi_preopens.zig#} 6999 7000 {#shell_samp#}$ wasmtime --dir=. wasi_preopens.wasm 7001 0: stdin 7002 1: stdout 7003 2: stderr 7004 3: . 7005 {#end_shell_samp#} 7006 {#header_close#} 7007 {#header_close#} 7008 {#header_open|Targets#} 7009 <p> 7010 <strong>Target</strong> refers to the computer that will be used to run an executable. 7011 It is composed of the CPU architecture, the set of enabled CPU features, operating system, 7012 minimum and maximum operating system version, ABI, and ABI version. 7013 </p> 7014 <p> 7015 Zig is a general-purpose programming language which means that it is designed to 7016 generate optimal code for a large set of targets. The command <code>zig targets</code> 7017 provides information about all of the targets the compiler is aware of.</p> 7018 <p>When no target option is provided to the compiler, the default choice 7019 is to target the <strong>host computer</strong>, meaning that the 7020 resulting executable will be <em>unsuitable for copying to a different 7021 computer</em>. In order to copy an executable to another computer, the compiler 7022 needs to know about the target requirements via the <code>-target</code> option. 7023 </p> 7024 <p> 7025 The Zig Standard Library ({#syntax#}@import("std"){#endsyntax#}) has 7026 cross-platform abstractions, making the same source code viable on many targets. 7027 Some code is more portable than other code. In general, Zig code is extremely 7028 portable compared to other programming languages. 7029 </p> 7030 <p> 7031 Each platform requires its own implementations to make Zig's 7032 cross-platform abstractions work. These implementations are at various 7033 degrees of completion. Each tagged release of the compiler comes with 7034 release notes that provide the full support table for each target. 7035 </p> 7036 {#header_close#} 7037 {#header_open|Style Guide#} 7038 <p> 7039 These coding conventions are not enforced by the compiler, but they are shipped in 7040 this documentation along with the compiler in order to provide a point of 7041 reference, should anyone wish to point to an authority on agreed upon Zig 7042 coding style. 7043 </p> 7044 {#header_open|Avoid Redundancy in Names#} 7045 <p>Avoid these words in type names:</p> 7046 <ul> 7047 <li>Value</li> 7048 <li>Data</li> 7049 <li>Context</li> 7050 <li>Manager</li> 7051 <li>utils, misc, or somebody's initials</li> 7052 </ul> 7053 <p>Everything is a value, all types are data, everything is context, all logic manages state. 7054 Nothing is communicated by using a word that applies to all types.</p> 7055 <p>Temptation to use "utilities", "miscellaneous", or somebody's initials 7056 is a failure to categorize, or more commonly, overcategorization. Such 7057 declarations can live at the root of a module that needs them with no 7058 namespace needed.</p> 7059 {#header_close#} 7060 7061 {#header_open|Avoid Redundant Names in Fully-Qualified Namespaces#} 7062 <p>Every declaration is assigned a <strong>fully qualified 7063 namespace</strong> by the compiler, creating a tree structure. Choose names based 7064 on the fully-qualified namespace, and avoid redundant name segments.</p> 7065 {#code|redundant_fqn.zig#} 7066 7067 <p>In this example, "json" is repeated in the fully-qualified namespace. The solution 7068 is to delete <code>Json</code> from <code>JsonValue</code>. In this example we have 7069 an empty struct named <code>json</code> but remember that files also act 7070 as part of the fully-qualified namespace.</p> 7071 <p>This example is an exception to the rule specified in {#link|Avoid Redundancy in Names#}. 7072 The meaning of the type has been reduced to its core: it is a json value. The name 7073 cannot be any more specific without being incorrect.</p> 7074 {#header_close#} 7075 7076 {#header_open|Whitespace#} 7077 <ul> 7078 <li> 7079 4 space indentation 7080 </li> 7081 <li> 7082 Open braces on same line, unless you need to wrap. 7083 </li> 7084 <li>If a list of things is longer than 2, put each item on its own line and 7085 exercise the ability to put an extra comma at the end. 7086 </li> 7087 <li> 7088 Line length: aim for 100; use common sense. 7089 </li> 7090 </ul> 7091 {#header_close#} 7092 {#header_open|Names#} 7093 <p> 7094 Roughly speaking: {#syntax#}camelCaseFunctionName{#endsyntax#}, {#syntax#}TitleCaseTypeName{#endsyntax#}, 7095 {#syntax#}snake_case_variable_name{#endsyntax#}. More precisely: 7096 </p> 7097 <ul> 7098 <li> 7099 If {#syntax#}x{#endsyntax#} is a {#syntax#}type{#endsyntax#} 7100 then {#syntax#}x{#endsyntax#} should be {#syntax#}TitleCase{#endsyntax#}, unless it 7101 is a {#syntax#}struct{#endsyntax#} with 0 fields and is never meant to be instantiated, 7102 in which case it is considered to be a "namespace" and uses {#syntax#}snake_case{#endsyntax#}. 7103 </li> 7104 <li> 7105 If {#syntax#}x{#endsyntax#} is callable, and {#syntax#}x{#endsyntax#}'s return type is 7106 {#syntax#}type{#endsyntax#}, then {#syntax#}x{#endsyntax#} should be {#syntax#}TitleCase{#endsyntax#}. 7107 </li> 7108 <li> 7109 If {#syntax#}x{#endsyntax#} is otherwise callable, then {#syntax#}x{#endsyntax#} should 7110 be {#syntax#}camelCase{#endsyntax#}. 7111 </li> 7112 <li> 7113 Otherwise, {#syntax#}x{#endsyntax#} should be {#syntax#}snake_case{#endsyntax#}. 7114 </li> 7115 </ul> 7116 <p> 7117 Acronyms, initialisms, proper nouns, or any other word that has capitalization 7118 rules in written English are subject to naming conventions just like any other 7119 word. Even acronyms that are only 2 letters long are subject to these 7120 conventions. 7121 </p> 7122 <p> 7123 File names fall into two categories: types and namespaces. If the file 7124 (implicitly a struct) has top level fields, it should be named like any 7125 other struct with fields using <code class="file">TitleCase</code>. Otherwise, 7126 it should use <code class="file">snake_case</code>. Directory names should be 7127 <code class="file">snake_case</code>. 7128 </p> 7129 <p> 7130 These are general rules of thumb; if it makes sense to do something different, 7131 do what makes sense. For example, if there is an established convention such as 7132 {#syntax#}ENOENT{#endsyntax#}, follow the established convention. 7133 </p> 7134 {#header_close#} 7135 {#header_open|Examples#} 7136 {#syntax_block|zig|style_example.zig#} 7137 const namespace_name = @import("dir_name/file_name.zig"); 7138 const TypeName = @import("dir_name/TypeName.zig"); 7139 var global_var: i32 = undefined; 7140 const const_name = 42; 7141 const primitive_type_alias = f32; 7142 const string_alias = []u8; 7143 7144 const StructName = struct { 7145 field: i32, 7146 }; 7147 const StructAlias = StructName; 7148 7149 fn functionName(param_name: TypeName) void { 7150 var functionPointer = functionName; 7151 functionPointer(); 7152 functionPointer = otherFunction; 7153 functionPointer(); 7154 } 7155 const functionAlias = functionName; 7156 7157 fn ListTemplateFunction(comptime ChildType: type, comptime fixed_size: usize) type { 7158 return List(ChildType, fixed_size); 7159 } 7160 7161 fn ShortList(comptime T: type, comptime n: usize) type { 7162 return struct { 7163 field_name: [n]T, 7164 fn methodName() void {} 7165 }; 7166 } 7167 7168 // The word XML loses its casing when used in Zig identifiers. 7169 const xml_document = 7170 \\<?xml version="1.0" encoding="UTF-8"?> 7171 \\<document> 7172 \\</document> 7173 ; 7174 const XmlParser = struct { 7175 field: i32, 7176 }; 7177 7178 // The initials BE (Big Endian) are just another word in Zig identifier names. 7179 fn readU32Be() u32 {} 7180 {#end_syntax_block#} 7181 <p> 7182 See the {#link|Zig Standard Library#} for more examples. 7183 </p> 7184 {#header_close#} 7185 {#header_open|Doc Comment Guidance#} 7186 <ul> 7187 <li>Omit any information that is redundant based on the name of the thing being documented.</li> 7188 <li>Duplicating information onto multiple similar functions is encouraged because it helps IDEs and other tools provide better help text.</li> 7189 <li>Use the word <strong>assume</strong> to indicate invariants that cause <em>unchecked</em> {#link|Illegal Behavior#} when violated.</li> 7190 <li>Use the word <strong>assert</strong> to indicate invariants that cause <em>safety-checked</em> {#link|Illegal Behavior#} when violated.</li> 7191 </ul> 7192 {#header_close#} 7193 {#header_close#} 7194 {#header_open|Source Encoding#} 7195 <p>Zig source code is encoded in UTF-8. An invalid UTF-8 byte sequence results in a compile error.</p> 7196 <p>Throughout all zig source code (including in comments), some code points are never allowed:</p> 7197 <ul> 7198 <li>Ascii control characters, except for U+000a (LF), U+000d (CR), and U+0009 (HT): U+0000 - U+0008, U+000b - U+000c, U+000e - U+0001f, U+007f.</li> 7199 <li>Non-Ascii Unicode line endings: U+0085 (NEL), U+2028 (LS), U+2029 (PS).</li> 7200 </ul> 7201 <p> 7202 LF (byte value 0x0a, code point U+000a, {#syntax#}'\n'{#endsyntax#}) is the line terminator in Zig source code. 7203 This byte value terminates every line of zig source code except the last line of the file. 7204 It is recommended that non-empty source files end with an empty line, which means the last byte would be 0x0a (LF). 7205 </p> 7206 <p> 7207 Each LF may be immediately preceded by a single CR (byte value 0x0d, code point U+000d, {#syntax#}'\r'{#endsyntax#}) 7208 to form a Windows style line ending, but this is discouraged. Note that in multiline strings, CRLF sequences will 7209 be encoded as LF when compiled into a zig program. 7210 A CR in any other context is not allowed. 7211 </p> 7212 <p> 7213 HT hard tabs (byte value 0x09, code point U+0009, {#syntax#}'\t'{#endsyntax#}) are interchangeable with 7214 SP spaces (byte value 0x20, code point U+0020, {#syntax#}' '{#endsyntax#}) as a token separator, 7215 but use of hard tabs is discouraged. See {#link|Grammar#}. 7216 </p> 7217 <p> 7218 For compatibility with other tools, the compiler ignores a UTF-8-encoded byte order mark (U+FEFF) 7219 if it is the first Unicode code point in the source text. A byte order mark is not allowed anywhere else in the source. 7220 </p> 7221 <p> 7222 Note that running <kbd>zig fmt</kbd> on a source file will implement all recommendations mentioned here. 7223 </p> 7224 <p> 7225 Note that a tool reading Zig source code can make assumptions if the source code is assumed to be correct Zig code. 7226 For example, when identifying the ends of lines, a tool can use a naive search such as <code>/\n/</code>, 7227 or an <a href="https://msdn.microsoft.com/en-us/library/dd409797.aspx">advanced</a> 7228 search such as <code>/\r\n?|[\n\u0085\u2028\u2029]/</code>, and in either case line endings will be correctly identified. 7229 For another example, when identifying the whitespace before the first token on a line, 7230 a tool can either use a naive search such as <code>/[ \t]/</code>, 7231 or an <a href="https://tc39.es/ecma262/#sec-characterclassescape">advanced</a> search such as <code>/\s/</code>, 7232 and in either case whitespace will be correctly identified. 7233 </p> 7234 {#header_close#} 7235 7236 {#header_open|Keyword Reference#} 7237 <div class="table-wrapper"> 7238 <table> 7239 <thead> 7240 <tr> 7241 <th scope="col">Keyword</th> 7242 <th scope="col">Description</th> 7243 </tr> 7244 </thead> 7245 <tbody> 7246 <tr> 7247 <th scope="row"> 7248 <pre>{#syntax#}addrspace{#endsyntax#}</pre> 7249 </th> 7250 <td> 7251 The {#syntax#}addrspace{#endsyntax#} keyword. 7252 <ul> 7253 <li>TODO add documentation for addrspace</li> 7254 </ul> 7255 </td> 7256 </tr> 7257 <tr> 7258 <th scope="row"> 7259 <pre>{#syntax#}align{#endsyntax#}</pre> 7260 </th> 7261 <td> 7262 {#syntax#}align{#endsyntax#} can be used to specify the alignment of a pointer. 7263 It can also be used after a variable or function declaration to specify the alignment of pointers to that variable or function. 7264 <ul> 7265 <li>See also {#link|Alignment#}</li> 7266 </ul> 7267 </td> 7268 </tr> 7269 <tr> 7270 <th scope="row"> 7271 <pre>{#syntax#}allowzero{#endsyntax#}</pre> 7272 </th> 7273 <td> 7274 The pointer attribute {#syntax#}allowzero{#endsyntax#} allows a pointer to have address zero. 7275 <ul> 7276 <li>See also {#link|allowzero#}</li> 7277 </ul> 7278 </td> 7279 </tr> 7280 <tr> 7281 <th scope="row"> 7282 <pre>{#syntax#}and{#endsyntax#}</pre> 7283 </th> 7284 <td> 7285 The boolean operator {#syntax#}and{#endsyntax#}. 7286 <ul> 7287 <li>See also {#link|Operators#}</li> 7288 </ul> 7289 </td> 7290 </tr> 7291 <tr> 7292 <th scope="row"> 7293 <pre>{#syntax#}anyframe{#endsyntax#}</pre> 7294 </th> 7295 <td> 7296 {#syntax#}anyframe{#endsyntax#} can be used as a type for variables which hold pointers to function frames. 7297 <ul> 7298 <li>See also {#link|Async Functions#}</li> 7299 </ul> 7300 </td> 7301 </tr> 7302 <tr> 7303 <th scope="row"> 7304 <pre>{#syntax#}anytype{#endsyntax#}</pre> 7305 </th> 7306 <td> 7307 Function parameters can be declared with {#syntax#}anytype{#endsyntax#} in place of the type. 7308 The type will be inferred where the function is called. 7309 <ul> 7310 <li>See also {#link|Function Parameter Type Inference#}</li> 7311 </ul> 7312 </td> 7313 </tr> 7314 <tr> 7315 <th scope="row"> 7316 <pre>{#syntax#}asm{#endsyntax#}</pre> 7317 </th> 7318 <td> 7319 {#syntax#}asm{#endsyntax#} begins an inline assembly expression. This allows for directly controlling the machine code generated on compilation. 7320 <ul> 7321 <li>See also {#link|Assembly#}</li> 7322 </ul> 7323 </td> 7324 </tr> 7325 <tr> 7326 <th scope="row"> 7327 <pre>{#syntax#}break{#endsyntax#}</pre> 7328 </th> 7329 <td> 7330 {#syntax#}break{#endsyntax#} can be used with a block label to return a value from the block. 7331 It can also be used to exit a loop before iteration completes naturally. 7332 <ul> 7333 <li>See also {#link|Blocks#}, {#link|while#}, {#link|for#}</li> 7334 </ul> 7335 </td> 7336 </tr> 7337 <tr> 7338 <th scope="row"> 7339 <pre>{#syntax#}callconv{#endsyntax#}</pre> 7340 </th> 7341 <td> 7342 {#syntax#}callconv{#endsyntax#} can be used to specify the calling convention in a function type. 7343 <ul> 7344 <li>See also {#link|Functions#}</li> 7345 </ul> 7346 </td> 7347 </tr> 7348 <tr> 7349 <th scope="row"> 7350 <pre>{#syntax#}catch{#endsyntax#}</pre> 7351 </th> 7352 <td> 7353 {#syntax#}catch{#endsyntax#} can be used to evaluate an expression if the expression before it evaluates to an error. 7354 The expression after the {#syntax#}catch{#endsyntax#} can optionally capture the error value. 7355 <ul> 7356 <li>See also {#link|catch#}, {#link|Operators#}</li> 7357 </ul> 7358 </td> 7359 </tr> 7360 <tr> 7361 <th scope="row"> 7362 <pre>{#syntax#}comptime{#endsyntax#}</pre> 7363 </th> 7364 <td> 7365 {#syntax#}comptime{#endsyntax#} before a declaration can be used to label variables or function parameters as known at compile time. 7366 It can also be used to guarantee an expression is run at compile time. 7367 <ul> 7368 <li>See also {#link|comptime#}</li> 7369 </ul> 7370 </td> 7371 </tr> 7372 <tr> 7373 <th scope="row"> 7374 <pre>{#syntax#}const{#endsyntax#}</pre> 7375 </th> 7376 <td> 7377 {#syntax#}const{#endsyntax#} declares a variable that can not be modified. 7378 Used as a pointer attribute, it denotes the value referenced by the pointer cannot be modified. 7379 <ul> 7380 <li>See also {#link|Variables#}</li> 7381 </ul> 7382 </td> 7383 </tr> 7384 <tr> 7385 <th scope="row"> 7386 <pre>{#syntax#}continue{#endsyntax#}</pre> 7387 </th> 7388 <td> 7389 {#syntax#}continue{#endsyntax#} can be used in a loop to jump back to the beginning of the loop. 7390 <ul> 7391 <li>See also {#link|while#}, {#link|for#}</li> 7392 </ul> 7393 </td> 7394 </tr> 7395 <tr> 7396 <th scope="row"> 7397 <pre>{#syntax#}defer{#endsyntax#}</pre> 7398 </th> 7399 <td> 7400 {#syntax#}defer{#endsyntax#} will execute an expression when control flow leaves the current block. 7401 <ul> 7402 <li>See also {#link|defer#}</li> 7403 </ul> 7404 </td> 7405 </tr> 7406 <tr> 7407 <th scope="row"> 7408 <pre>{#syntax#}else{#endsyntax#}</pre> 7409 </th> 7410 <td> 7411 {#syntax#}else{#endsyntax#} can be used to provide an alternate branch for {#syntax#}if{#endsyntax#}, {#syntax#}switch{#endsyntax#}, 7412 {#syntax#}while{#endsyntax#}, and {#syntax#}for{#endsyntax#} expressions. 7413 <ul> 7414 <li>If used after an if expression, the else branch will be executed if the test value returns false, null, or an error.</li> 7415 <li>If used within a switch expression, the else branch will be executed if the test value matches no other cases.</li> 7416 <li>If used after a loop expression, the else branch will be executed if the loop finishes without breaking.</li> 7417 <li>See also {#link|if#}, {#link|switch#}, {#link|while#}, {#link|for#}</li> 7418 </ul> 7419 </td> 7420 </tr> 7421 <tr> 7422 <th scope="row"> 7423 <pre>{#syntax#}enum{#endsyntax#}</pre> 7424 </th> 7425 <td> 7426 {#syntax#}enum{#endsyntax#} defines an enum type. 7427 <ul> 7428 <li>See also {#link|enum#}</li> 7429 </ul> 7430 </td> 7431 </tr> 7432 <tr> 7433 <th scope="row"> 7434 <pre>{#syntax#}errdefer{#endsyntax#}</pre> 7435 </th> 7436 <td> 7437 {#syntax#}errdefer{#endsyntax#} will execute an expression when control flow leaves the current block if the function returns an error, the errdefer expression can capture the unwrapped value. 7438 <ul> 7439 <li>See also {#link|errdefer#}</li> 7440 </ul> 7441 </td> 7442 </tr> 7443 <tr> 7444 <th scope="row"> 7445 <pre>{#syntax#}error{#endsyntax#}</pre> 7446 </th> 7447 <td> 7448 {#syntax#}error{#endsyntax#} defines an error type. 7449 <ul> 7450 <li>See also {#link|Errors#}</li> 7451 </ul> 7452 </td> 7453 </tr> 7454 <tr> 7455 <th scope="row"> 7456 <pre>{#syntax#}export{#endsyntax#}</pre> 7457 </th> 7458 <td> 7459 {#syntax#}export{#endsyntax#} makes a function or variable externally visible in the generated object file. 7460 Exported functions default to the C calling convention. 7461 <ul> 7462 <li>See also {#link|Functions#}</li> 7463 </ul> 7464 </td> 7465 </tr> 7466 <tr> 7467 <th scope="row"> 7468 <pre>{#syntax#}extern{#endsyntax#}</pre> 7469 </th> 7470 <td> 7471 {#syntax#}extern{#endsyntax#} can be used to declare a function or variable that will be resolved at link time, when linking statically 7472 or at runtime, when linking dynamically. 7473 <ul> 7474 <li>See also {#link|Functions#}</li> 7475 </ul> 7476 </td> 7477 </tr> 7478 <tr> 7479 <th scope="row"> 7480 <pre>{#syntax#}fn{#endsyntax#}</pre> 7481 </th> 7482 <td> 7483 {#syntax#}fn{#endsyntax#} declares a function. 7484 <ul> 7485 <li>See also {#link|Functions#}</li> 7486 </ul> 7487 </td> 7488 </tr> 7489 <tr> 7490 <th scope="row"> 7491 <pre>{#syntax#}for{#endsyntax#}</pre> 7492 </th> 7493 <td> 7494 A {#syntax#}for{#endsyntax#} expression can be used to iterate over the elements of a slice, array, or tuple. 7495 <ul> 7496 <li>See also {#link|for#}</li> 7497 </ul> 7498 </td> 7499 </tr> 7500 <tr> 7501 <th scope="row"> 7502 <pre>{#syntax#}if{#endsyntax#}</pre> 7503 </th> 7504 <td> 7505 An {#syntax#}if{#endsyntax#} expression can test boolean expressions, optional values, or error unions. 7506 For optional values or error unions, the if expression can capture the unwrapped value. 7507 <ul> 7508 <li>See also {#link|if#}</li> 7509 </ul> 7510 </td> 7511 </tr> 7512 <tr> 7513 <th scope="row"> 7514 <pre>{#syntax#}inline{#endsyntax#}</pre> 7515 </th> 7516 <td> 7517 {#syntax#}inline{#endsyntax#} can be used to label a loop expression such that it will be unrolled at compile time. 7518 It can also be used to force a function to be inlined at all call sites. 7519 <ul> 7520 <li>See also {#link|inline while#}, {#link|inline for#}, {#link|Functions#}</li> 7521 </ul> 7522 </td> 7523 </tr> 7524 <tr> 7525 <th scope="row"> 7526 <pre>{#syntax#}linksection{#endsyntax#}</pre> 7527 </th> 7528 <td> 7529 The {#syntax#}linksection{#endsyntax#} keyword can be used to specify what section the function or global variable will be put into (e.g. <code>.text</code>). 7530 </td> 7531 </tr> 7532 <tr> 7533 <th scope="row"> 7534 <pre>{#syntax#}noalias{#endsyntax#}</pre> 7535 </th> 7536 <td> 7537 The {#syntax#}noalias{#endsyntax#} keyword. 7538 <ul> 7539 <li>TODO add documentation for noalias</li> 7540 </ul> 7541 </td> 7542 </tr> 7543 <tr> 7544 <th scope="row"> 7545 <pre>{#syntax#}noinline{#endsyntax#}</pre> 7546 </th> 7547 <td> 7548 {#syntax#}noinline{#endsyntax#} disallows function to be inlined in all call sites. 7549 <ul> 7550 <li>See also {#link|Functions#}</li> 7551 </ul> 7552 </td> 7553 </tr> 7554 <tr> 7555 <th scope="row"> 7556 <pre>{#syntax#}nosuspend{#endsyntax#}</pre> 7557 </th> 7558 <td> 7559 The {#syntax#}nosuspend{#endsyntax#} keyword can be used in front of a block, statement or expression, to mark a scope where no suspension points are reached. 7560 In particular, inside a {#syntax#}nosuspend{#endsyntax#} scope: 7561 <ul> 7562 <li>Using the {#syntax#}suspend{#endsyntax#} keyword results in a compile error.</li> 7563 <li>Using {#syntax#}await{#endsyntax#} on a function frame which hasn't completed yet results in safety-checked {#link|Illegal Behavior#}.</li> 7564 <li>Calling an async function may result in safety-checked {#link|Illegal Behavior#}, because it's equivalent to <code>await async some_async_fn()</code>, which contains an {#syntax#}await{#endsyntax#}.</li> 7565 </ul> 7566 Code inside a {#syntax#}nosuspend{#endsyntax#} scope does not cause the enclosing function to become an {#link|async function|Async Functions#}. 7567 <ul> 7568 <li>See also {#link|Async Functions#}</li> 7569 </ul> 7570 </td> 7571 </tr> 7572 <tr> 7573 <th scope="row"> 7574 <pre>{#syntax#}opaque{#endsyntax#}</pre> 7575 </th> 7576 <td> 7577 {#syntax#}opaque{#endsyntax#} defines an opaque type. 7578 <ul> 7579 <li>See also {#link|opaque#}</li> 7580 </ul> 7581 </td> 7582 </tr> 7583 <tr> 7584 <th scope="row"> 7585 <pre>{#syntax#}or{#endsyntax#}</pre> 7586 </th> 7587 <td> 7588 The boolean operator {#syntax#}or{#endsyntax#}. 7589 <ul> 7590 <li>See also {#link|Operators#}</li> 7591 </ul> 7592 </td> 7593 </tr> 7594 <tr> 7595 <th scope="row"> 7596 <pre>{#syntax#}orelse{#endsyntax#}</pre> 7597 </th> 7598 <td> 7599 {#syntax#}orelse{#endsyntax#} can be used to evaluate an expression if the expression before it evaluates to null. 7600 <ul> 7601 <li>See also {#link|Optionals#}, {#link|Operators#}</li> 7602 </ul> 7603 </td> 7604 </tr> 7605 <tr> 7606 <th scope="row"> 7607 <pre>{#syntax#}packed{#endsyntax#}</pre> 7608 </th> 7609 <td> 7610 The {#syntax#}packed{#endsyntax#} keyword before a struct definition changes the struct's in-memory layout 7611 to the guaranteed {#syntax#}packed{#endsyntax#} layout. 7612 <ul> 7613 <li>See also {#link|packed struct#}</li> 7614 </ul> 7615 </td> 7616 </tr> 7617 <tr> 7618 <th scope="row"> 7619 <pre>{#syntax#}pub{#endsyntax#}</pre> 7620 </th> 7621 <td> 7622 The {#syntax#}pub{#endsyntax#} in front of a top level declaration makes the declaration available 7623 to reference from a different file than the one it is declared in. 7624 <ul> 7625 <li>See also {#link|import#}</li> 7626 </ul> 7627 </td> 7628 </tr> 7629 <tr> 7630 <th scope="row"> 7631 <pre>{#syntax#}resume{#endsyntax#}</pre> 7632 </th> 7633 <td> 7634 {#syntax#}resume{#endsyntax#} will continue execution of a function frame after the point the function was suspended. 7635 </td> 7636 </tr> 7637 <tr> 7638 <th scope="row"> 7639 <pre>{#syntax#}return{#endsyntax#}</pre> 7640 </th> 7641 <td> 7642 {#syntax#}return{#endsyntax#} exits a function with a value. 7643 <ul> 7644 <li>See also {#link|Functions#}</li> 7645 </ul> 7646 </td> 7647 </tr> 7648 <tr> 7649 <th scope="row"> 7650 <pre>{#syntax#}struct{#endsyntax#}</pre> 7651 </th> 7652 <td> 7653 {#syntax#}struct{#endsyntax#} defines a struct. 7654 <ul> 7655 <li>See also {#link|struct#}</li> 7656 </ul> 7657 </td> 7658 </tr> 7659 <tr> 7660 <th scope="row"> 7661 <pre>{#syntax#}suspend{#endsyntax#}</pre> 7662 </th> 7663 <td> 7664 {#syntax#}suspend{#endsyntax#} will cause control flow to return to the call site or resumer of the function. 7665 {#syntax#}suspend{#endsyntax#} can also be used before a block within a function, 7666 to allow the function access to its frame before control flow returns to the call site. 7667 </td> 7668 </tr> 7669 <tr> 7670 <th scope="row"> 7671 <pre>{#syntax#}switch{#endsyntax#}</pre> 7672 </th> 7673 <td> 7674 A {#syntax#}switch{#endsyntax#} expression can be used to test values of a common type. 7675 {#syntax#}switch{#endsyntax#} cases can capture field values of a {#link|Tagged union#}. 7676 <ul> 7677 <li>See also {#link|switch#}</li> 7678 </ul> 7679 </td> 7680 </tr> 7681 <tr> 7682 <th scope="row"> 7683 <pre>{#syntax#}test{#endsyntax#}</pre> 7684 </th> 7685 <td> 7686 The {#syntax#}test{#endsyntax#} keyword can be used to denote a top-level block of code 7687 used to make sure behavior meets expectations. 7688 <ul> 7689 <li>See also {#link|Zig Test#}</li> 7690 </ul> 7691 </td> 7692 </tr> 7693 <tr> 7694 <th scope="row"> 7695 <pre>{#syntax#}threadlocal{#endsyntax#}</pre> 7696 </th> 7697 <td> 7698 {#syntax#}threadlocal{#endsyntax#} can be used to specify a variable as thread-local. 7699 <ul> 7700 <li>See also {#link|Thread Local Variables#}</li> 7701 </ul> 7702 </td> 7703 </tr> 7704 <tr> 7705 <th scope="row"> 7706 <pre>{#syntax#}try{#endsyntax#}</pre> 7707 </th> 7708 <td> 7709 {#syntax#}try{#endsyntax#} evaluates an error union expression. 7710 If it is an error, it returns from the current function with the same error. 7711 Otherwise, the expression results in the unwrapped value. 7712 <ul> 7713 <li>See also {#link|try#}</li> 7714 </ul> 7715 </td> 7716 </tr> 7717 <tr> 7718 <th scope="row"> 7719 <pre>{#syntax#}union{#endsyntax#}</pre> 7720 </th> 7721 <td> 7722 {#syntax#}union{#endsyntax#} defines a union. 7723 <ul> 7724 <li>See also {#link|union#}</li> 7725 </ul> 7726 </td> 7727 </tr> 7728 <tr> 7729 <th scope="row"> 7730 <pre>{#syntax#}unreachable{#endsyntax#}</pre> 7731 </th> 7732 <td> 7733 {#syntax#}unreachable{#endsyntax#} can be used to assert that control flow will never happen upon a particular location. 7734 Depending on the build mode, {#syntax#}unreachable{#endsyntax#} may emit a panic. 7735 <ul> 7736 <li>Emits a panic in {#syntax#}Debug{#endsyntax#} and {#syntax#}ReleaseSafe{#endsyntax#} mode, or when using <kbd>zig test</kbd>.</li> 7737 <li>Does not emit a panic in {#syntax#}ReleaseFast{#endsyntax#} and {#syntax#}ReleaseSmall{#endsyntax#} mode.</li> 7738 <li>See also {#link|unreachable#}</li> 7739 </ul> 7740 </td> 7741 </tr> 7742 <tr> 7743 <th scope="row"> 7744 <pre>{#syntax#}var{#endsyntax#}</pre> 7745 </th> 7746 <td> 7747 {#syntax#}var{#endsyntax#} declares a variable that may be modified. 7748 <ul> 7749 <li>See also {#link|Variables#}</li> 7750 </ul> 7751 </td> 7752 </tr> 7753 <tr> 7754 <th scope="row"> 7755 <pre>{#syntax#}volatile{#endsyntax#}</pre> 7756 </th> 7757 <td> 7758 {#syntax#}volatile{#endsyntax#} can be used to denote loads or stores of a pointer have side effects. 7759 It can also modify an inline assembly expression to denote it has side effects. 7760 <ul> 7761 <li>See also {#link|volatile#}, {#link|Assembly#}</li> 7762 </ul> 7763 </td> 7764 </tr> 7765 <tr> 7766 <th scope="row"> 7767 <pre>{#syntax#}while{#endsyntax#}</pre> 7768 </th> 7769 <td> 7770 A {#syntax#}while{#endsyntax#} expression can be used to repeatedly test a boolean, optional, or error union expression, 7771 and cease looping when that expression evaluates to false, null, or an error, respectively. 7772 <ul> 7773 <li>See also {#link|while#}</li> 7774 </ul> 7775 </td> 7776 </tr> 7777 </tbody> 7778 </table> 7779 </div> 7780 {#header_close#} 7781 7782 {#header_open|Appendix#} 7783 {#header_open|Containers#} 7784 <p> 7785 A <em>container</em> in Zig is any syntactical construct that acts as a namespace to hold {#link|variable|Container Level Variables#} and {#link|function|Functions#} declarations. 7786 Containers are also type definitions which can be instantiated. 7787 {#link|Structs|struct#}, {#link|enums|enum#}, {#link|unions|union#}, {#link|opaques|opaque#}, and even Zig source files themselves are containers. 7788 </p> 7789 <p> 7790 Although containers (except Zig source files) use curly braces to surround their definition, they should not be confused with {#link|blocks|Blocks#} or functions. 7791 Containers do not contain statements. 7792 </p> 7793 {#header_close#} 7794 7795 {#header_open|Grammar#} 7796 {#syntax_block|peg|grammar.y#} 7797 Root <- skip container_doc_comment? ContainerMembers eof 7798 7799 # *** Top level *** 7800 ContainerMembers <- ContainerDeclaration* (ContainerField COMMA)* (ContainerField / ContainerDeclaration*) 7801 7802 ContainerDeclaration <- TestDecl / ComptimeDecl / doc_comment? KEYWORD_pub? Decl 7803 7804 TestDecl <- KEYWORD_test (STRINGLITERALSINGLE / IDENTIFIER)? Block 7805 7806 ComptimeDecl <- KEYWORD_comptime Block 7807 7808 Decl 7809 <- (KEYWORD_export / KEYWORD_extern STRINGLITERALSINGLE? / KEYWORD_inline / KEYWORD_noinline)? FnProto (SEMICOLON / Block) 7810 / (KEYWORD_export / KEYWORD_extern STRINGLITERALSINGLE?)? KEYWORD_threadlocal? GlobalVarDecl 7811 7812 FnProto <- KEYWORD_fn IDENTIFIER? LPAREN ParamDeclList RPAREN ByteAlign? AddrSpace? LinkSection? CallConv? EXCLAMATIONMARK? TypeExpr 7813 7814 VarDeclProto <- (KEYWORD_const / KEYWORD_var) IDENTIFIER (COLON TypeExpr)? ByteAlign? AddrSpace? LinkSection? 7815 7816 GlobalVarDecl <- VarDeclProto (EQUAL Expr)? SEMICOLON 7817 7818 ContainerField <- doc_comment? KEYWORD_comptime? !KEYWORD_fn (IDENTIFIER COLON)? TypeExpr ByteAlign? (EQUAL Expr)? 7819 7820 # *** Block Level *** 7821 Statement 7822 <- KEYWORD_comptime ComptimeStatement 7823 / KEYWORD_nosuspend BlockExprStatement 7824 / KEYWORD_suspend BlockExprStatement 7825 / KEYWORD_defer BlockExprStatement 7826 / KEYWORD_errdefer Payload? BlockExprStatement 7827 / IfStatement 7828 / LabeledStatement 7829 / SwitchExpr 7830 / VarDeclExprStatement 7831 7832 ComptimeStatement 7833 <- BlockExpr 7834 / VarDeclExprStatement 7835 7836 IfStatement 7837 <- IfPrefix BlockExpr ( KEYWORD_else Payload? Statement )? 7838 / IfPrefix AssignExpr ( SEMICOLON / KEYWORD_else Payload? Statement ) 7839 7840 LabeledStatement <- BlockLabel? (Block / LoopStatement) 7841 7842 LoopStatement <- KEYWORD_inline? (ForStatement / WhileStatement) 7843 7844 ForStatement 7845 <- ForPrefix BlockExpr ( KEYWORD_else Statement )? 7846 / ForPrefix AssignExpr ( SEMICOLON / KEYWORD_else Statement ) 7847 7848 WhileStatement 7849 <- WhilePrefix BlockExpr ( KEYWORD_else Payload? Statement )? 7850 / WhilePrefix AssignExpr ( SEMICOLON / KEYWORD_else Payload? Statement ) 7851 7852 BlockExprStatement 7853 <- BlockExpr 7854 / AssignExpr SEMICOLON 7855 7856 BlockExpr <- BlockLabel? Block 7857 7858 # An expression, assignment, or any destructure, as a statement. 7859 VarDeclExprStatement 7860 <- VarDeclProto (COMMA (VarDeclProto / Expr))* EQUAL Expr SEMICOLON 7861 / Expr (AssignOp Expr / (COMMA (VarDeclProto / Expr))+ EQUAL Expr)? SEMICOLON 7862 7863 # *** Expression Level *** 7864 7865 # An assignment or a destructure whose LHS are all lvalue expressions. 7866 AssignExpr <- Expr (AssignOp Expr / (COMMA Expr)+ EQUAL Expr)? 7867 7868 SingleAssignExpr <- Expr (AssignOp Expr)? 7869 7870 Expr <- BoolOrExpr 7871 7872 BoolOrExpr <- BoolAndExpr (KEYWORD_or BoolAndExpr)* 7873 7874 BoolAndExpr <- CompareExpr (KEYWORD_and CompareExpr)* 7875 7876 CompareExpr <- BitwiseExpr (CompareOp BitwiseExpr)? 7877 7878 BitwiseExpr <- BitShiftExpr (BitwiseOp BitShiftExpr)* 7879 7880 BitShiftExpr <- AdditionExpr (BitShiftOp AdditionExpr)* 7881 7882 AdditionExpr <- MultiplyExpr (AdditionOp MultiplyExpr)* 7883 7884 MultiplyExpr <- PrefixExpr (MultiplyOp PrefixExpr)* 7885 7886 PrefixExpr <- PrefixOp* PrimaryExpr 7887 7888 PrimaryExpr 7889 <- AsmExpr 7890 / IfExpr 7891 / KEYWORD_break BreakLabel? Expr? 7892 / KEYWORD_comptime Expr 7893 / KEYWORD_nosuspend Expr 7894 / KEYWORD_continue BreakLabel? 7895 / KEYWORD_resume Expr 7896 / KEYWORD_return Expr? 7897 / BlockLabel? LoopExpr 7898 / Block 7899 / CurlySuffixExpr 7900 7901 IfExpr <- IfPrefix Expr (KEYWORD_else Payload? Expr)? 7902 7903 Block <- LBRACE Statement* RBRACE 7904 7905 LoopExpr <- KEYWORD_inline? (ForExpr / WhileExpr) 7906 7907 ForExpr <- ForPrefix Expr (KEYWORD_else Expr)? 7908 7909 WhileExpr <- WhilePrefix Expr (KEYWORD_else Payload? Expr)? 7910 7911 CurlySuffixExpr <- TypeExpr InitList? 7912 7913 InitList 7914 <- LBRACE FieldInit (COMMA FieldInit)* COMMA? RBRACE 7915 / LBRACE Expr (COMMA Expr)* COMMA? RBRACE 7916 / LBRACE RBRACE 7917 7918 TypeExpr <- PrefixTypeOp* ErrorUnionExpr 7919 7920 ErrorUnionExpr <- SuffixExpr (EXCLAMATIONMARK TypeExpr)? 7921 7922 SuffixExpr 7923 <- PrimaryTypeExpr (SuffixOp / FnCallArguments)* 7924 7925 PrimaryTypeExpr 7926 <- BUILTINIDENTIFIER FnCallArguments 7927 / CHAR_LITERAL 7928 / ContainerDecl 7929 / DOT IDENTIFIER 7930 / DOT InitList 7931 / ErrorSetDecl 7932 / FLOAT 7933 / FnProto 7934 / GroupedExpr 7935 / LabeledTypeExpr 7936 / IDENTIFIER 7937 / IfTypeExpr 7938 / INTEGER 7939 / KEYWORD_comptime TypeExpr 7940 / KEYWORD_error DOT IDENTIFIER 7941 / KEYWORD_anyframe 7942 / KEYWORD_unreachable 7943 / STRINGLITERAL 7944 / SwitchExpr 7945 7946 ContainerDecl <- (KEYWORD_extern / KEYWORD_packed)? ContainerDeclAuto 7947 7948 ErrorSetDecl <- KEYWORD_error LBRACE IdentifierList RBRACE 7949 7950 GroupedExpr <- LPAREN Expr RPAREN 7951 7952 IfTypeExpr <- IfPrefix TypeExpr (KEYWORD_else Payload? TypeExpr)? 7953 7954 LabeledTypeExpr 7955 <- BlockLabel Block 7956 / BlockLabel? LoopTypeExpr 7957 7958 LoopTypeExpr <- KEYWORD_inline? (ForTypeExpr / WhileTypeExpr) 7959 7960 ForTypeExpr <- ForPrefix TypeExpr (KEYWORD_else TypeExpr)? 7961 7962 WhileTypeExpr <- WhilePrefix TypeExpr (KEYWORD_else Payload? TypeExpr)? 7963 7964 SwitchExpr <- KEYWORD_switch LPAREN Expr RPAREN LBRACE SwitchProngList RBRACE 7965 7966 # *** Assembly *** 7967 AsmExpr <- KEYWORD_asm KEYWORD_volatile? LPAREN Expr AsmOutput? RPAREN 7968 7969 AsmOutput <- COLON AsmOutputList AsmInput? 7970 7971 AsmOutputItem <- LBRACKET IDENTIFIER RBRACKET STRINGLITERAL LPAREN (MINUSRARROW TypeExpr / IDENTIFIER) RPAREN 7972 7973 AsmInput <- COLON AsmInputList AsmClobbers? 7974 7975 AsmInputItem <- LBRACKET IDENTIFIER RBRACKET STRINGLITERAL LPAREN Expr RPAREN 7976 7977 AsmClobbers <- COLON Expr 7978 7979 # *** Helper grammar *** 7980 BreakLabel <- COLON IDENTIFIER 7981 7982 BlockLabel <- IDENTIFIER COLON 7983 7984 FieldInit <- DOT IDENTIFIER EQUAL Expr 7985 7986 WhileContinueExpr <- COLON LPAREN AssignExpr RPAREN 7987 7988 LinkSection <- KEYWORD_linksection LPAREN Expr RPAREN 7989 7990 AddrSpace <- KEYWORD_addrspace LPAREN Expr RPAREN 7991 7992 # Fn specific 7993 CallConv <- KEYWORD_callconv LPAREN Expr RPAREN 7994 7995 ParamDecl 7996 <- doc_comment? (KEYWORD_noalias / KEYWORD_comptime)? (IDENTIFIER COLON)? ParamType 7997 / DOT3 7998 7999 ParamType 8000 <- KEYWORD_anytype 8001 / TypeExpr 8002 8003 # Control flow prefixes 8004 IfPrefix <- KEYWORD_if LPAREN Expr RPAREN PtrPayload? 8005 8006 WhilePrefix <- KEYWORD_while LPAREN Expr RPAREN PtrPayload? WhileContinueExpr? 8007 8008 ForPrefix <- KEYWORD_for LPAREN ForArgumentsList RPAREN PtrListPayload 8009 8010 # Payloads 8011 Payload <- PIPE IDENTIFIER PIPE 8012 8013 PtrPayload <- PIPE ASTERISK? IDENTIFIER PIPE 8014 8015 PtrIndexPayload <- PIPE ASTERISK? IDENTIFIER (COMMA IDENTIFIER)? PIPE 8016 8017 PtrListPayload <- PIPE ASTERISK? IDENTIFIER (COMMA ASTERISK? IDENTIFIER)* COMMA? PIPE 8018 8019 # Switch specific 8020 SwitchProng <- KEYWORD_inline? SwitchCase EQUALRARROW PtrIndexPayload? SingleAssignExpr 8021 8022 SwitchCase 8023 <- SwitchItem (COMMA SwitchItem)* COMMA? 8024 / KEYWORD_else 8025 8026 SwitchItem <- Expr (DOT3 Expr)? 8027 8028 # For specific 8029 ForArgumentsList <- ForItem (COMMA ForItem)* COMMA? 8030 8031 ForItem <- Expr (DOT2 Expr?)? 8032 8033 # Operators 8034 AssignOp 8035 <- ASTERISKEQUAL 8036 / ASTERISKPIPEEQUAL 8037 / SLASHEQUAL 8038 / PERCENTEQUAL 8039 / PLUSEQUAL 8040 / PLUSPIPEEQUAL 8041 / MINUSEQUAL 8042 / MINUSPIPEEQUAL 8043 / LARROW2EQUAL 8044 / LARROW2PIPEEQUAL 8045 / RARROW2EQUAL 8046 / AMPERSANDEQUAL 8047 / CARETEQUAL 8048 / PIPEEQUAL 8049 / ASTERISKPERCENTEQUAL 8050 / PLUSPERCENTEQUAL 8051 / MINUSPERCENTEQUAL 8052 / EQUAL 8053 8054 CompareOp 8055 <- EQUALEQUAL 8056 / EXCLAMATIONMARKEQUAL 8057 / LARROW 8058 / RARROW 8059 / LARROWEQUAL 8060 / RARROWEQUAL 8061 8062 BitwiseOp 8063 <- AMPERSAND 8064 / CARET 8065 / PIPE 8066 / KEYWORD_orelse 8067 / KEYWORD_catch Payload? 8068 8069 BitShiftOp 8070 <- LARROW2 8071 / RARROW2 8072 / LARROW2PIPE 8073 8074 AdditionOp 8075 <- PLUS 8076 / MINUS 8077 / PLUS2 8078 / PLUSPERCENT 8079 / MINUSPERCENT 8080 / PLUSPIPE 8081 / MINUSPIPE 8082 8083 MultiplyOp 8084 <- PIPE2 8085 / ASTERISK 8086 / SLASH 8087 / PERCENT 8088 / ASTERISK2 8089 / ASTERISKPERCENT 8090 / ASTERISKPIPE 8091 8092 PrefixOp 8093 <- EXCLAMATIONMARK 8094 / MINUS 8095 / TILDE 8096 / MINUSPERCENT 8097 / AMPERSAND 8098 / KEYWORD_try 8099 8100 PrefixTypeOp 8101 <- QUESTIONMARK 8102 / KEYWORD_anyframe MINUSRARROW 8103 / SliceTypeStart (ByteAlign / AddrSpace / KEYWORD_const / KEYWORD_volatile / KEYWORD_allowzero)* 8104 / PtrTypeStart (AddrSpace / KEYWORD_align LPAREN Expr (COLON Expr COLON Expr)? RPAREN / KEYWORD_const / KEYWORD_volatile / KEYWORD_allowzero)* 8105 / ArrayTypeStart 8106 8107 SuffixOp 8108 <- LBRACKET Expr (DOT2 (Expr? (COLON Expr)?)?)? RBRACKET 8109 / DOT IDENTIFIER 8110 / DOTASTERISK 8111 / DOTQUESTIONMARK 8112 8113 FnCallArguments <- LPAREN ExprList RPAREN 8114 8115 # Ptr specific 8116 SliceTypeStart <- LBRACKET (COLON Expr)? RBRACKET 8117 8118 PtrTypeStart 8119 <- ASTERISK 8120 / ASTERISK2 8121 / LBRACKET ASTERISK (LETTERC / COLON Expr)? RBRACKET 8122 8123 ArrayTypeStart <- LBRACKET Expr (COLON Expr)? RBRACKET 8124 8125 # ContainerDecl specific 8126 ContainerDeclAuto <- ContainerDeclType LBRACE container_doc_comment? ContainerMembers RBRACE 8127 8128 ContainerDeclType 8129 <- KEYWORD_struct (LPAREN Expr RPAREN)? 8130 / KEYWORD_opaque 8131 / KEYWORD_enum (LPAREN Expr RPAREN)? 8132 / KEYWORD_union (LPAREN (KEYWORD_enum (LPAREN Expr RPAREN)? / Expr) RPAREN)? 8133 8134 # Alignment 8135 ByteAlign <- KEYWORD_align LPAREN Expr RPAREN 8136 8137 # Lists 8138 IdentifierList <- (doc_comment? IDENTIFIER COMMA)* (doc_comment? IDENTIFIER)? 8139 8140 SwitchProngList <- (SwitchProng COMMA)* SwitchProng? 8141 8142 AsmOutputList <- (AsmOutputItem COMMA)* AsmOutputItem? 8143 8144 AsmInputList <- (AsmInputItem COMMA)* AsmInputItem? 8145 8146 StringList <- (STRINGLITERAL COMMA)* STRINGLITERAL? 8147 8148 ParamDeclList <- (ParamDecl COMMA)* ParamDecl? 8149 8150 ExprList <- (Expr COMMA)* Expr? 8151 8152 # *** Tokens *** 8153 eof <- !. 8154 bin <- [01] 8155 bin_ <- '_'? bin 8156 oct <- [0-7] 8157 oct_ <- '_'? oct 8158 hex <- [0-9a-fA-F] 8159 hex_ <- '_'? hex 8160 dec <- [0-9] 8161 dec_ <- '_'? dec 8162 8163 bin_int <- bin bin_* 8164 oct_int <- oct oct_* 8165 dec_int <- dec dec_* 8166 hex_int <- hex hex_* 8167 8168 ox80_oxBF <- [\200-\277] 8169 oxF4 <- '\364' 8170 ox80_ox8F <- [\200-\217] 8171 oxF1_oxF3 <- [\361-\363] 8172 oxF0 <- '\360' 8173 ox90_0xBF <- [\220-\277] 8174 oxEE_oxEF <- [\356-\357] 8175 oxED <- '\355' 8176 ox80_ox9F <- [\200-\237] 8177 oxE1_oxEC <- [\341-\354] 8178 oxE0 <- '\340' 8179 oxA0_oxBF <- [\240-\277] 8180 oxC2_oxDF <- [\302-\337] 8181 8182 # From https://lemire.me/blog/2018/05/09/how-quickly-can-you-check-that-a-string-is-valid-unicode-utf-8/ 8183 # First Byte Second Byte Third Byte Fourth Byte 8184 # [0x00,0x7F] 8185 # [0xC2,0xDF] [0x80,0xBF] 8186 # 0xE0 [0xA0,0xBF] [0x80,0xBF] 8187 # [0xE1,0xEC] [0x80,0xBF] [0x80,0xBF] 8188 # 0xED [0x80,0x9F] [0x80,0xBF] 8189 # [0xEE,0xEF] [0x80,0xBF] [0x80,0xBF] 8190 # 0xF0 [0x90,0xBF] [0x80,0xBF] [0x80,0xBF] 8191 # [0xF1,0xF3] [0x80,0xBF] [0x80,0xBF] [0x80,0xBF] 8192 # 0xF4 [0x80,0x8F] [0x80,0xBF] [0x80,0xBF] 8193 8194 mb_utf8_literal <- 8195 oxF4 ox80_ox8F ox80_oxBF ox80_oxBF 8196 / oxF1_oxF3 ox80_oxBF ox80_oxBF ox80_oxBF 8197 / oxF0 ox90_0xBF ox80_oxBF ox80_oxBF 8198 / oxEE_oxEF ox80_oxBF ox80_oxBF 8199 / oxED ox80_ox9F ox80_oxBF 8200 / oxE1_oxEC ox80_oxBF ox80_oxBF 8201 / oxE0 oxA0_oxBF ox80_oxBF 8202 / oxC2_oxDF ox80_oxBF 8203 8204 ascii_char_not_nl_slash_squote <- [\000-\011\013-\046\050-\133\135-\177] 8205 8206 char_escape 8207 <- "\\x" hex hex 8208 / "\\u{" hex+ "}" 8209 / "\\" [nr\\t'"] 8210 char_char 8211 <- mb_utf8_literal 8212 / char_escape 8213 / ascii_char_not_nl_slash_squote 8214 8215 string_char 8216 <- char_escape 8217 / [^\\"\n] 8218 8219 container_doc_comment <- ('//!' [^\n]* [ \n]* skip)+ 8220 doc_comment <- ('///' [^\n]* [ \n]* skip)+ 8221 line_comment <- '//' ![!/][^\n]* / '////' [^\n]* 8222 line_string <- ("\\\\" [^\n]* [ \n]*)+ 8223 skip <- ([ \n] / line_comment)* 8224 8225 CHAR_LITERAL <- "'" char_char "'" skip 8226 FLOAT 8227 <- "0x" hex_int "." hex_int ([pP] [-+]? dec_int)? skip 8228 / dec_int "." dec_int ([eE] [-+]? dec_int)? skip 8229 / "0x" hex_int [pP] [-+]? dec_int skip 8230 / dec_int [eE] [-+]? dec_int skip 8231 INTEGER 8232 <- "0b" bin_int skip 8233 / "0o" oct_int skip 8234 / "0x" hex_int skip 8235 / dec_int skip 8236 STRINGLITERALSINGLE <- "\"" string_char* "\"" skip 8237 STRINGLITERAL 8238 <- STRINGLITERALSINGLE 8239 / (line_string skip)+ 8240 IDENTIFIER 8241 <- !keyword [A-Za-z_] [A-Za-z0-9_]* skip 8242 / "@" STRINGLITERALSINGLE 8243 BUILTINIDENTIFIER <- "@"[A-Za-z_][A-Za-z0-9_]* skip 8244 8245 8246 AMPERSAND <- '&' ![=] skip 8247 AMPERSANDEQUAL <- '&=' skip 8248 ASTERISK <- '*' ![*%=|] skip 8249 ASTERISK2 <- '**' skip 8250 ASTERISKEQUAL <- '*=' skip 8251 ASTERISKPERCENT <- '*%' ![=] skip 8252 ASTERISKPERCENTEQUAL <- '*%=' skip 8253 ASTERISKPIPE <- '*|' ![=] skip 8254 ASTERISKPIPEEQUAL <- '*|=' skip 8255 CARET <- '^' ![=] skip 8256 CARETEQUAL <- '^=' skip 8257 COLON <- ':' skip 8258 COMMA <- ',' skip 8259 DOT <- '.' ![*.?] skip 8260 DOT2 <- '..' ![.] skip 8261 DOT3 <- '...' skip 8262 DOTASTERISK <- '.*' skip 8263 DOTQUESTIONMARK <- '.?' skip 8264 EQUAL <- '=' ![>=] skip 8265 EQUALEQUAL <- '==' skip 8266 EQUALRARROW <- '=>' skip 8267 EXCLAMATIONMARK <- '!' ![=] skip 8268 EXCLAMATIONMARKEQUAL <- '!=' skip 8269 LARROW <- '<' ![<=] skip 8270 LARROW2 <- '<<' ![=|] skip 8271 LARROW2EQUAL <- '<<=' skip 8272 LARROW2PIPE <- '<<|' ![=] skip 8273 LARROW2PIPEEQUAL <- '<<|=' skip 8274 LARROWEQUAL <- '<=' skip 8275 LBRACE <- '{' skip 8276 LBRACKET <- '[' skip 8277 LPAREN <- '(' skip 8278 MINUS <- '-' ![%=>|] skip 8279 MINUSEQUAL <- '-=' skip 8280 MINUSPERCENT <- '-%' ![=] skip 8281 MINUSPERCENTEQUAL <- '-%=' skip 8282 MINUSPIPE <- '-|' ![=] skip 8283 MINUSPIPEEQUAL <- '-|=' skip 8284 MINUSRARROW <- '->' skip 8285 PERCENT <- '%' ![=] skip 8286 PERCENTEQUAL <- '%=' skip 8287 PIPE <- '|' ![|=] skip 8288 PIPE2 <- '||' skip 8289 PIPEEQUAL <- '|=' skip 8290 PLUS <- '+' ![%+=|] skip 8291 PLUS2 <- '++' skip 8292 PLUSEQUAL <- '+=' skip 8293 PLUSPERCENT <- '+%' ![=] skip 8294 PLUSPERCENTEQUAL <- '+%=' skip 8295 PLUSPIPE <- '+|' ![=] skip 8296 PLUSPIPEEQUAL <- '+|=' skip 8297 LETTERC <- 'c' skip 8298 QUESTIONMARK <- '?' skip 8299 RARROW <- '>' ![>=] skip 8300 RARROW2 <- '>>' ![=] skip 8301 RARROW2EQUAL <- '>>=' skip 8302 RARROWEQUAL <- '>=' skip 8303 RBRACE <- '}' skip 8304 RBRACKET <- ']' skip 8305 RPAREN <- ')' skip 8306 SEMICOLON <- ';' skip 8307 SLASH <- '/' ![=] skip 8308 SLASHEQUAL <- '/=' skip 8309 TILDE <- '~' skip 8310 8311 end_of_word <- ![a-zA-Z0-9_] skip 8312 KEYWORD_addrspace <- 'addrspace' end_of_word 8313 KEYWORD_align <- 'align' end_of_word 8314 KEYWORD_allowzero <- 'allowzero' end_of_word 8315 KEYWORD_and <- 'and' end_of_word 8316 KEYWORD_anyframe <- 'anyframe' end_of_word 8317 KEYWORD_anytype <- 'anytype' end_of_word 8318 KEYWORD_asm <- 'asm' end_of_word 8319 KEYWORD_break <- 'break' end_of_word 8320 KEYWORD_callconv <- 'callconv' end_of_word 8321 KEYWORD_catch <- 'catch' end_of_word 8322 KEYWORD_comptime <- 'comptime' end_of_word 8323 KEYWORD_const <- 'const' end_of_word 8324 KEYWORD_continue <- 'continue' end_of_word 8325 KEYWORD_defer <- 'defer' end_of_word 8326 KEYWORD_else <- 'else' end_of_word 8327 KEYWORD_enum <- 'enum' end_of_word 8328 KEYWORD_errdefer <- 'errdefer' end_of_word 8329 KEYWORD_error <- 'error' end_of_word 8330 KEYWORD_export <- 'export' end_of_word 8331 KEYWORD_extern <- 'extern' end_of_word 8332 KEYWORD_fn <- 'fn' end_of_word 8333 KEYWORD_for <- 'for' end_of_word 8334 KEYWORD_if <- 'if' end_of_word 8335 KEYWORD_inline <- 'inline' end_of_word 8336 KEYWORD_noalias <- 'noalias' end_of_word 8337 KEYWORD_nosuspend <- 'nosuspend' end_of_word 8338 KEYWORD_noinline <- 'noinline' end_of_word 8339 KEYWORD_opaque <- 'opaque' end_of_word 8340 KEYWORD_or <- 'or' end_of_word 8341 KEYWORD_orelse <- 'orelse' end_of_word 8342 KEYWORD_packed <- 'packed' end_of_word 8343 KEYWORD_pub <- 'pub' end_of_word 8344 KEYWORD_resume <- 'resume' end_of_word 8345 KEYWORD_return <- 'return' end_of_word 8346 KEYWORD_linksection <- 'linksection' end_of_word 8347 KEYWORD_struct <- 'struct' end_of_word 8348 KEYWORD_suspend <- 'suspend' end_of_word 8349 KEYWORD_switch <- 'switch' end_of_word 8350 KEYWORD_test <- 'test' end_of_word 8351 KEYWORD_threadlocal <- 'threadlocal' end_of_word 8352 KEYWORD_try <- 'try' end_of_word 8353 KEYWORD_union <- 'union' end_of_word 8354 KEYWORD_unreachable <- 'unreachable' end_of_word 8355 KEYWORD_var <- 'var' end_of_word 8356 KEYWORD_volatile <- 'volatile' end_of_word 8357 KEYWORD_while <- 'while' end_of_word 8358 8359 keyword <- KEYWORD_addrspace / KEYWORD_align / KEYWORD_allowzero / KEYWORD_and 8360 / KEYWORD_anyframe / KEYWORD_anytype / KEYWORD_asm 8361 / KEYWORD_break / KEYWORD_callconv / KEYWORD_catch 8362 / KEYWORD_comptime / KEYWORD_const / KEYWORD_continue / KEYWORD_defer 8363 / KEYWORD_else / KEYWORD_enum / KEYWORD_errdefer / KEYWORD_error / KEYWORD_export 8364 / KEYWORD_extern / KEYWORD_fn / KEYWORD_for / KEYWORD_if 8365 / KEYWORD_inline / KEYWORD_noalias / KEYWORD_nosuspend / KEYWORD_noinline 8366 / KEYWORD_opaque / KEYWORD_or / KEYWORD_orelse / KEYWORD_packed 8367 / KEYWORD_pub / KEYWORD_resume / KEYWORD_return / KEYWORD_linksection 8368 / KEYWORD_struct / KEYWORD_suspend / KEYWORD_switch / KEYWORD_test 8369 / KEYWORD_threadlocal / KEYWORD_try / KEYWORD_union / KEYWORD_unreachable 8370 / KEYWORD_var / KEYWORD_volatile / KEYWORD_while 8371 {#end_syntax_block#} 8372 {#header_close#} 8373 {#header_open|Zen#} 8374 <ul> 8375 <li>Communicate intent precisely.</li> 8376 <li>Edge cases matter.</li> 8377 <li>Favor reading code over writing code.</li> 8378 <li>Only one obvious way to do things.</li> 8379 <li>Runtime crashes are better than bugs.</li> 8380 <li>Compile errors are better than runtime crashes.</li> 8381 <li>Incremental improvements.</li> 8382 <li>Avoid local maximums.</li> 8383 <li>Reduce the amount one must remember.</li> 8384 <li>Focus on code rather than style.</li> 8385 <li>Resource allocation may fail; resource deallocation must succeed.</li> 8386 <li>Memory is a resource.</li> 8387 <li>Together we serve the users.</li> 8388 </ul> 8389 {#header_close#} 8390 {#header_close#} 8391 </main></div> 8392 </div> 8393 </body> 8394 </html>