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