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