Zig is a general-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
- Robust
- Behavior is correct even for edge cases such as out of memory.
- Optimal
- Write programs the best way they can behave and perform.
- Reusable
- The same code works in many environments which have different constraints.
- Maintainable
- Precisely communicate intent to the compiler and other programmers. The language imposes a low overhead to reading code and is resilient to changing requirements and environments.
Often the most efficient way to learn something new is to see examples, so this documentation shows how to use each of Zig's features. It is all on one page so you can search with your browser's search tool.
The code samples in this document are compiled and tested as part of the main test suite of Zig.
This HTML document depends on no external files, so you can use it offline.
{#header_close#} {#header_open|Zig Standard Library#}The Zig Standard Library has its own documentation.
Zig's Standard Library contains commonly used algorithms, data structures, and definitions to help you build programs or libraries. You will see many examples of Zig's Standard Library used in this documentation. To learn more about the Zig Standard Library, visit the link above.
{#header_close#} {#header_open|Hello World#} {#code_begin|exe|hello#} const std = @import("std"); pub fn main() !void { const stdout = std.io.getStdOut().writer(); try stdout.print("Hello, {s}!\n", .{"world"}); } {#code_end#}The Zig code sample above demonstrates one way to create a program that will output: Hello, world!.
The code sample shows the contents of a file named hello.zig
. Files storing Zig
source code are {#link|UTF-8 encoded|Source Encoding#} text files. The files storing
Zig source code are usually named with the .zig
extension.
Following the hello.zig
Zig code sample, the {#link|Zig Build System#} is used
to build an executable program from the hello.zig
source code. Then, the
hello
program is executed showing its output Hello, world!. The
lines beginning with $ represent command line prompts and a command.
Everything else is program output.
The code sample begins by adding the {#link|Zig Standard Library#} to the build using the {#link|@import#} builtin function. The {#syntax#}@import("std"){#endsyntax#} function call creates a structure that represents the Zig Standard Library. The code then {#link|declares|Container Level Variables#} a {#link|constant identifier|Assignment#}, named {#syntax#}std{#endsyntax#}, that gives access to the features of the Zig Standard Library.
Next, a {#link|public function|Functions#}, {#syntax#}pub fn{#endsyntax#}, named {#syntax#}main{#endsyntax#} is declared. The {#syntax#}main{#endsyntax#} function is necessary because it tells the Zig compiler where the start of the program exists. Programs designed to be executed will need a {#syntax#}pub fn main{#endsyntax#} function.
A function is a block of any number of statements and expressions that, as a whole, perform a task. Functions may or may not return data after they are done performing their task. If a function cannot perform its task, it might return an error. Zig makes all of this explicit.
In the hello.zig
code sample, the main
function is declared
with the {#syntax#}!void{#endsyntax#} return type. This return type is known as an {#link|Error Union Type#}.
This syntax tells the Zig compiler that the function will either return an
error or a value. An error union type combines an {#link|Error Set Type#} and any other data type
(e.g. a {#link|Primitive Type|Primitive Types#} or a user-defined type such as a {#link|struct#}, {#link|enum#}, or {#link|union#}).
The full form of an error union type is
<error set type>
{#syntax#}!{#endsyntax#}<any data type>
. In the code
sample, the error set type is not explicitly written on the left side of the {#syntax#}!{#endsyntax#} operator.
When written this way, the error set type is an {#link|inferred error set type|Inferred Error Sets#}. The
{#syntax#}void{#endsyntax#} after the {#syntax#}!{#endsyntax#} operator
tells the compiler that the function will not return a value under normal circumstances (i.e. when no errors occur).
In Zig, a function's block of statements and expressions are surrounded by an open curly-brace {
and
close curly-brace }
. Inside of the {#syntax#}main{#endsyntax#} function are expressions that perform
the task of outputting Hello, world! to standard output.
First, a constant identifier, {#syntax#}stdout{#endsyntax#}, is initialized to represent standard output's writer. Then, the program tries to print the Hello, world! message to standard output.
Functions sometimes need information to perform their task. In Zig, information is passed to functions between an open parenthesis {#syntax#}({#endsyntax#} and a close parenthesis {#syntax#}){#endsyntax#} placed after the function's name. This information is also known as arguments. When there are multiple arguments passed to a function, they are separated by commas {#syntax#},{#endsyntax#}.
The two arguments passed to the {#syntax#}stdout.print(){#endsyntax#} function, {#syntax#}"Hello, {s}!\n"{#endsyntax#}
and {#syntax#}.{"world"}{#endsyntax#}, are evaluated at {#link|compile-time|comptime#}. The code sample is
purposely written to show how to perform {#link|string|String Literals and Unicode Code Point Literals#}
substitution in the {#syntax#}print{#endsyntax#} function. The curly-braces inside of the first argument
are substituted with the compile-time known value inside of the second argument
(known as an {#link|anonymous struct literal|Anonymous Struct Literals#}). The \n
inside of the double-quotes of the first argument is the {#link|escape sequence|Escape Sequences#} for the
newline character. The {#link|try#} expression evaluates the result of {#syntax#}stdout.print{#endsyntax#}.
If the result is an error, then the {#syntax#}try{#endsyntax#} expression will return from
{#syntax#}main{#endsyntax#} with the error. Otherwise, the program will continue. In this case, there are no
more statements or expressions left to execute in the {#syntax#}main{#endsyntax#} function, so the program exits.
In Zig, the standard output writer's {#syntax#}print{#endsyntax#} function is allowed to fail because
it is actually a function defined as part of a generic Writer. Consider a generic Writer that
represents writing data to a file. When the disk is full, a write to the file will fail.
However, we typically do not expect writing text to the standard output to fail. To avoid having
to handle the failure case of printing to standard output, you can use alternate functions: the
functions in {#syntax#}std.log{#endsyntax#} for proper logging or the {#syntax#}std.debug.print{#endsyntax#} function.
This documentation will use the latter option to print to standard error (stderr) and silently return
on failure. The next code sample, hello_again.zig
demonstrates the use of
{#syntax#}std.debug.print{#endsyntax#}.
Note that you can leave off the {#syntax#}!{#endsyntax#} from the return type because {#syntax#}std.debug.print{#endsyntax#} cannot fail.
{#see_also|Values|@import|Errors|Root Source File|Source Encoding#} {#header_close#} {#header_open|Comments#} {#code_begin|exe|comments#} const print = @import("std").debug.print; pub fn main() void { // Comments in Zig start with "//" and end at the next LF byte (end of line). // The line below is a comment and won't be executed. //print("Hello?", .{}); print("Hello, world!\n", .{}); // another comment } {#code_end#}
There are no multiline comments in Zig (e.g. like /* */
comments in C). This helps allow Zig to have the property that each line
of code can be tokenized out of context.
A doc comment is one that begins with exactly three slashes (i.e. {#syntax#}///{#endsyntax#} but not {#syntax#}////{#endsyntax#}); multiple doc comments in a row are merged together to form a multiline doc comment. The doc comment documents whatever immediately follows it.
{#code_begin|syntax|doc_comments#} /// A structure for storing a timestamp, with nanosecond precision (this is a /// multiline doc comment). const Timestamp = struct { /// The number of seconds since the epoch (this is also a doc comment). seconds: i64, // signed so we can represent pre-1970 (not a doc comment) /// The number of nanoseconds past the second (doc comment again). nanos: u32, /// Returns a `Timestamp` struct representing the Unix epoch; that is, the /// moment of 1970 Jan 1 00:00:00 UTC (this is a doc comment too). pub fn unixEpoch() Timestamp { return Timestamp{ .seconds = 0, .nanos = 0, }; } }; {#code_end#}Doc comments are only allowed in certain places; eventually, it will become a compile error to have a doc comment in an unexpected place, such as in the middle of an expression, or just before a non-doc comment.
{#header_close#} {#header_open|Top-Level Doc Comments#}User documentation that doesn't belong to whatever immediately follows it, like {#link|container|Containers#}-level documentation, goes in top-level doc comments. A top-level doc comment is one that begins with two slashes and an exclamation point: {#syntax#}//!{#endsyntax#}.
{#code_begin|syntax|tldoc_comments#} //! This module provides functions for retrieving the current date and //! time with varying degrees of precision and accuracy. It does not //! depend on libc, but will use functions from it if available. {#code_end#} {#header_close#} {#header_close#} {#header_open|Values#} {#code_begin|exe|values#} // Top-level declarations are order-independent: const print = std.debug.print; const std = @import("std"); const os = std.os; const assert = std.debug.assert; pub fn main() void { // integers const one_plus_one: i32 = 1 + 1; print("1 + 1 = {}\n", .{one_plus_one}); // floats const seven_div_three: f32 = 7.0 / 3.0; print("7.0 / 3.0 = {}\n", .{seven_div_three}); // boolean print("{}\n{}\n{}\n", .{ true and false, true or false, !true, }); // optional var optional_value: ?[]const u8 = null; assert(optional_value == null); print("\noptional 1\ntype: {}\nvalue: {?s}\n", .{ @TypeOf(optional_value), optional_value, }); optional_value = "hi"; assert(optional_value != null); print("\noptional 2\ntype: {}\nvalue: {?s}\n", .{ @TypeOf(optional_value), optional_value, }); // error union var number_or_error: anyerror!i32 = error.ArgNotFound; print("\nerror union 1\ntype: {}\nvalue: {!}\n", .{ @TypeOf(number_or_error), number_or_error, }); number_or_error = 1234; print("\nerror union 2\ntype: {}\nvalue: {!}\n", .{ @TypeOf(number_or_error), number_or_error, }); } {#code_end#} {#header_open|Primitive Types#}Type | C Equivalent | Description |
---|---|---|
{#syntax#}i8{#endsyntax#} | int8_t |
signed 8-bit integer |
{#syntax#}u8{#endsyntax#} | uint8_t |
unsigned 8-bit integer |
{#syntax#}i16{#endsyntax#} | int16_t |
signed 16-bit integer |
{#syntax#}u16{#endsyntax#} | uint16_t |
unsigned 16-bit integer |
{#syntax#}i32{#endsyntax#} | int32_t |
signed 32-bit integer |
{#syntax#}u32{#endsyntax#} | uint32_t |
unsigned 32-bit integer |
{#syntax#}i64{#endsyntax#} | int64_t |
signed 64-bit integer |
{#syntax#}u64{#endsyntax#} | uint64_t |
unsigned 64-bit integer |
{#syntax#}i128{#endsyntax#} | __int128 |
signed 128-bit integer |
{#syntax#}u128{#endsyntax#} | unsigned __int128 |
unsigned 128-bit integer |
{#syntax#}isize{#endsyntax#} | intptr_t |
signed pointer sized integer |
{#syntax#}usize{#endsyntax#} | uintptr_t , size_t |
unsigned pointer sized integer. Also see #5185 |
{#syntax#}c_short{#endsyntax#} | short |
for ABI compatibility with C |
{#syntax#}c_ushort{#endsyntax#} | unsigned short |
for ABI compatibility with C |
{#syntax#}c_int{#endsyntax#} | int |
for ABI compatibility with C |
{#syntax#}c_uint{#endsyntax#} | unsigned int |
for ABI compatibility with C |
{#syntax#}c_long{#endsyntax#} | long |
for ABI compatibility with C |
{#syntax#}c_ulong{#endsyntax#} | unsigned long |
for ABI compatibility with C |
{#syntax#}c_longlong{#endsyntax#} | long long |
for ABI compatibility with C |
{#syntax#}c_ulonglong{#endsyntax#} | unsigned long long |
for ABI compatibility with C |
{#syntax#}c_longdouble{#endsyntax#} | long double |
for ABI compatibility with C |
{#syntax#}f16{#endsyntax#} | _Float16 |
16-bit floating point (10-bit mantissa) IEEE-754-2008 binary16 |
{#syntax#}f32{#endsyntax#} | float |
32-bit floating point (23-bit mantissa) IEEE-754-2008 binary32 |
{#syntax#}f64{#endsyntax#} | double |
64-bit floating point (52-bit mantissa) IEEE-754-2008 binary64 |
{#syntax#}f80{#endsyntax#} | double |
80-bit floating point (64-bit mantissa) IEEE-754-2008 80-bit extended precision |
{#syntax#}f128{#endsyntax#} | _Float128 |
128-bit floating point (112-bit mantissa) IEEE-754-2008 binary128 |
{#syntax#}bool{#endsyntax#} | bool |
{#syntax#}true{#endsyntax#} or {#syntax#}false{#endsyntax#} |
{#syntax#}anyopaque{#endsyntax#} | void |
Used for type-erased pointers. |
{#syntax#}void{#endsyntax#} | (none) | Always the value {#syntax#}void{}{#endsyntax#} |
{#syntax#}noreturn{#endsyntax#} | (none) | the type of {#syntax#}break{#endsyntax#}, {#syntax#}continue{#endsyntax#}, {#syntax#}return{#endsyntax#}, {#syntax#}unreachable{#endsyntax#}, and {#syntax#}while (true) {}{#endsyntax#} |
{#syntax#}type{#endsyntax#} | (none) | the type of types |
{#syntax#}anyerror{#endsyntax#} | (none) | an error code |
{#syntax#}comptime_int{#endsyntax#} | (none) | Only allowed for {#link|comptime#}-known values. The type of integer literals. |
{#syntax#}comptime_float{#endsyntax#} | (none) | Only allowed for {#link|comptime#}-known values. The type of float literals. |
In addition to the integer types above, arbitrary bit-width integers can be referenced by using
an identifier of i
or u
followed by digits. For example, the identifier
{#syntax#}i7{#endsyntax#} refers to a signed 7-bit integer. The maximum allowed bit-width of an
integer type is {#syntax#}65535{#endsyntax#}.
Name | Description |
---|---|
{#syntax#}true{#endsyntax#} and {#syntax#}false{#endsyntax#} | {#syntax#}bool{#endsyntax#} values |
{#syntax#}null{#endsyntax#} | used to set an optional type to {#syntax#}null{#endsyntax#} |
{#syntax#}undefined{#endsyntax#} | used to leave a value unspecified |
String literals are constant single-item {#link|Pointers#} to null-terminated byte arrays. The type of string literals encodes both the length, and the fact that they are null-terminated, and thus they can be {#link|coerced|Type Coercion#} to both {#link|Slices#} and {#link|Null-Terminated Pointers|Sentinel-Terminated Pointers#}. Dereferencing string literals converts them to {#link|Arrays#}.
The encoding of a string in Zig is de-facto assumed to be UTF-8.
Because Zig source code is {#link|UTF-8 encoded|Source Encoding#}, any non-ASCII bytes appearing within a string literal
in source code carry their UTF-8 meaning into the content of the string in the Zig program;
the bytes are not modified by the compiler.
However, it is possible to embed non-UTF-8 bytes into a string literal using \xNN
notation.
Unicode code point literals have type {#syntax#}comptime_int{#endsyntax#}, the same as {#link|Integer Literals#}. All {#link|Escape Sequences#} are valid in both string literals and Unicode code point literals.
In many other programming languages, a Unicode code point literal is called a "character literal". However, there is no precise technical definition of a "character" in recent versions of the Unicode specification (as of Unicode 13.0). In Zig, a Unicode code point literal corresponds to the Unicode definition of a code point.
{#code_begin|exe|string_literals#} const print = @import("std").debug.print; const mem = @import("std").mem; // will be used to compare bytes pub fn main() void { const bytes = "hello"; print("{}\n", .{@TypeOf(bytes)}); // *const [5:0]u8 print("{d}\n", .{bytes.len}); // 5 print("{c}\n", .{bytes[1]}); // 'e' print("{d}\n", .{bytes[5]}); // 0 print("{}\n", .{'e' == '\x65'}); // true print("{d}\n", .{'\u{1f4a9}'}); // 128169 print("{d}\n", .{'💯'}); // 128175 print("{}\n", .{mem.eql(u8, "hello", "h\x65llo")}); // true print("0x{x}\n", .{"\xff"[0]}); // non-UTF-8 strings are possible with \xNN notation. print("{u}\n", .{'⚡'}); } {#code_end#} {#see_also|Arrays|Source Encoding#} {#header_open|Escape Sequences#}Escape Sequence | Name |
---|---|
\n |
Newline |
\r |
Carriage Return |
\t |
Tab |
\\ |
Backslash |
\' |
Single Quote |
\" |
Double Quote |
\xNN |
hexadecimal 8-bit byte value (2 digits) |
\u{NNNNNN} |
hexadecimal Unicode code point UTF-8 encoded (1 or more digits) |
Note that the maximum valid Unicode point is {#syntax#}0x10ffff{#endsyntax#}.
{#header_close#} {#header_open|Multiline String Literals#}Multiline string literals have no escapes and can span across multiple lines. To start a multiline string literal, use the {#syntax#}\\{#endsyntax#} token. Just like a comment, the string literal goes until the end of the line. The end of the line is not included in the string literal. However, if the next line begins with {#syntax#}\\{#endsyntax#} then a newline is appended and the string literal continues.
{#code_begin|syntax|multiline_string_literals#} const hello_world_in_c = \\#includeUse the {#syntax#}const{#endsyntax#} keyword to assign a value to an identifier:
{#code_begin|exe_build_err|constant_identifier_cannot_change#} const x = 1234; fn foo() void { // It works at file scope as well as inside functions. const y = 5678; // Once assigned, an identifier cannot be changed. y += 1; } pub fn main() void { foo(); } {#code_end#}{#syntax#}const{#endsyntax#} applies to all of the bytes that the identifier immediately addresses. {#link|Pointers#} have their own const-ness.
If you need a variable that you can modify, use the {#syntax#}var{#endsyntax#} keyword:
{#code_begin|exe|mutable_var#} const print = @import("std").debug.print; pub fn main() void { var y: i32 = 5678; y += 1; print("{d}", .{y}); } {#code_end#}Variables must be initialized:
{#code_begin|exe_build_err|var_must_be_initialized#} pub fn main() void { var x: i32; x = 1; } {#code_end#} {#header_open|undefined#}Use {#syntax#}undefined{#endsyntax#} to leave variables uninitialized:
{#code_begin|exe|assign_undefined#} const print = @import("std").debug.print; pub fn main() void { var x: i32 = undefined; x = 1; print("{d}", .{x}); } {#code_end#}{#syntax#}undefined{#endsyntax#} can be {#link|coerced|Type Coercion#} to any type. Once this happens, it is no longer possible to detect that the value is {#syntax#}undefined{#endsyntax#}. {#syntax#}undefined{#endsyntax#} means the value could be anything, even something that is nonsense according to the type. Translated into English, {#syntax#}undefined{#endsyntax#} means "Not a meaningful value. Using this value would be a bug. The value will be unused, or overwritten before being used."
In {#link|Debug#} mode, Zig writes {#syntax#}0xaa{#endsyntax#} bytes to undefined memory. This is to catch bugs early, and to help detect use of undefined memory in a debugger. However, this behavior is only an implementation feature, not a language semantic, so it is not guaranteed to be observable to code.
{#header_close#} {#header_close#} {#header_close#} {#header_open|Zig Test#}Code written within one or more {#syntax#}test{#endsyntax#} declarations can be used to ensure behavior meets expectations:
{#code_begin|test|introducing_zig_test#} const std = @import("std"); test "expect addOne adds one to 41" { // The Standard Library contains useful functions to help create tests. // `expect` is a function that verifies its argument is true. // It will return an error if its argument is false to indicate a failure. // `try` is used to return an error to the test runner to notify it that the test failed. try std.testing.expect(addOne(41) == 42); } /// The function `addOne` adds one to the number given as its argument. fn addOne(number: i32) i32 { return number + 1; } {#code_end#}
The introducing_zig_test.zig
code sample tests the {#link|function|Functions#}
{#syntax#}addOne{#endsyntax#} to ensure that it returns {#syntax#}42{#endsyntax#} given the input
{#syntax#}41{#endsyntax#}. From this test's perspective, the {#syntax#}addOne{#endsyntax#} function is
said to be code under test.
zig test is a tool that creates and runs a test build. By default, it builds and runs an executable program using the default test runner provided by the {#link|Zig Standard Library#} as its main entry point. During the build, {#syntax#}test{#endsyntax#} declarations found while {#link|resolving|Root Source File#} the given Zig source file are included for the default test runner to run and report on.
The shell output shown above displays two lines after the zig test command. These lines are printed to standard error by the default test runner:
- Test [1/1] test "expect addOne adds one to 41"...
- Lines like this indicate which test, out of the total number of tests, is being run. In this case, [1/1] indicates that the first test, out of a total of one test, is being run. Note that, when the test runner program's standard error is output to the terminal, these lines are cleared when a test succeeds.
- All 1 tests passed.
- This line indicates the total number of tests that have passed.
Test declarations contain the {#link|keyword|Keyword Reference#} {#syntax#}test{#endsyntax#}, followed by an optional name written as a {#link|string literal|String Literals and Unicode Code Point Literals#}, followed by a {#link|block|Blocks#} containing any valid Zig code that is allowed in a {#link|function|Functions#}.
Test declarations are similar to {#link|Functions#}: they have a return type and a block of code. The implicit return type of {#syntax#}test{#endsyntax#} is the {#link|Error Union Type#} {#syntax#}anyerror!void{#endsyntax#}, and it cannot be changed. When a Zig source file is not built using the zig test tool, the test declarations are omitted from the build.
Test declarations can be written in the same file, where code under test is written, or in a separate Zig source file. Since test declarations are top-level declarations, they are order-independent and can be written before or after the code under test.
{#see_also|The Global Error Set|Grammar#} {#header_close#} {#header_open|Nested Container Tests#}When the zig test tool is building a test runner, only resolved {#syntax#}test{#endsyntax#} declarations are included in the build. Initially, only the given Zig source file's top-level declarations are resolved. Unless nested {#link|containers|Containers#} are referenced from a top-level test declaration, nested container tests will not be resolved.
The code sample below uses the {#syntax#}std.testing.refAllDecls(@This()){#endsyntax#} function call to reference all of the containers that are in the file including the imported Zig source file. The code sample also shows an alternative way to reference containers using the {#syntax#}_ = C;{#endsyntax#} syntax. This syntax tells the compiler to ignore the result of the expression on the right side of the assignment operator.
{#code_begin|test|testdecl_container_top_level#} const std = @import("std"); const expect = std.testing.expect; // Imported source file tests will run when referenced from a top-level test declaration. // The next line alone does not cause "introducing_zig_test.zig" tests to run. const imported_file = @import("introducing_zig_test.zig"); test { // To run nested container tests, either, call `refAllDecls` which will // reference all declarations located in the given argument. // `@This()` is a builtin function that returns the innermost container it is called from. // In this example, the innermost container is this file (implicitly a struct). std.testing.refAllDecls(@This()); // or, reference each container individually from a top-level test declaration. // The `_ = C;` syntax is a no-op reference to the identifier `C`. _ = S; _ = U; _ = @import("introducing_zig_test.zig"); } const S = struct { test "S demo test" { try expect(true); } const SE = enum { V, // This test won't run because its container (SE) is not referenced. test "This Test Won't Run" { try expect(false); } }; }; const U = union { // U is referenced by the file's top-level test declaration s: US, // and US is referenced here; therefore, "U.Us demo test" will run const US = struct { test "U.US demo test" { // This test is a top-level test declaration for the struct. // The struct is nested (declared) inside of a union. try expect(true); } }; test "U demo test" { try expect(true); } }; {#code_end#} {#header_close#} {#header_open|Test Failure#}The default test runner checks for an {#link|error|Errors#} returned from a test. When a test returns an error, the test is considered a failure and its {#link|error return trace|Error Return Traces#} is output to standard error. The total number of failures will be reported after all tests have run.
{#code_begin|test_err#} const std = @import("std"); test "expect this to fail" { try std.testing.expect(false); } test "expect this to succeed" { try std.testing.expect(true); } {#code_end#} {#header_close#} {#header_open|Skip Tests#}One way to skip tests is to filter them out by using the zig test command line parameter --test-filter [text]. This makes the test build only include tests whose name contains the supplied filter text. Note that non-named tests are run even when using the --test-filter [text] command line parameter.
To programmatically skip a test, make a {#syntax#}test{#endsyntax#} return the error {#syntax#}error.SkipZigTest{#endsyntax#} and the default test runner will consider the test as being skipped. The total number of skipped tests will be reported after all tests have run.
{#code_begin|test#} test "this will be skipped" { return error.SkipZigTest; } {#code_end#}The default test runner skips tests containing a {#link|suspend point|Async Functions#} while the test is running using the default, blocking IO mode. (The evented IO mode is enabled using the --test-evented-io command line parameter.)
{#code_begin|test|async_skip#} {#backend_stage1#} const std = @import("std"); test "async skip test" { var frame = async func(); const result = await frame; try std.testing.expect(result == 1); } fn func() i32 { suspend { resume @frame(); } return 1; } {#code_end#}In the code sample above, the test would not be skipped in blocking IO mode if the {#syntax#}nosuspend{#endsyntax#} keyword was used (see {#link|Async and Await#}).
{#header_close#} {#header_open|Report Memory Leaks#}When code allocates {#link|Memory#} using the {#link|Zig Standard Library#}'s testing allocator, {#syntax#}std.testing.allocator{#endsyntax#}, the default test runner will report any leaks that are found from using the testing allocator:
{#code_begin|test_err|1 tests leaked memory#} const std = @import("std"); test "detect leak" { var list = std.ArrayList(u21).init(std.testing.allocator); // missing `defer list.deinit();` try list.append('☔'); try std.testing.expect(list.items.len == 1); } {#code_end#} {#see_also|defer|Memory#} {#header_close#} {#header_open|Detecting Test Build#}Use the {#link|compile variable|Compile Variables#} {#syntax#}@import("builtin").is_test{#endsyntax#} to detect a test build:
{#code_begin|test|detect_test#} const std = @import("std"); const builtin = @import("builtin"); const expect = std.testing.expect; test "builtin.is_test" { try expect(isATest()); } fn isATest() bool { return builtin.is_test; } {#code_end#} {#header_close#} {#header_open|Test Output and Logging#}The default test runner and the Zig Standard Library's testing namespace output messages to standard error.
{#header_close#} {#header_open|The Testing Namespace#}
The Zig Standard Library's testing
namespace contains useful functions to help
you create tests. In addition to the expect
function, this document uses a couple of more functions
as exemplified here:
The Zig Standard Library also contains functions to compare {#link|Slices#}, strings, and more. See the rest of the {#syntax#}std.testing{#endsyntax#} namespace in the {#link|Zig Standard Library#} for more available functions.
{#header_close#} {#header_open|Test Tool Documentation#}zig test has a few command line parameters which affect the compilation. See zig test --help for a full list.
{#header_close#} {#header_close#} {#header_open|Variables#}A variable is a unit of {#link|Memory#} storage.
It is generally preferable to use {#syntax#}const{#endsyntax#} rather than {#syntax#}var{#endsyntax#} when declaring a variable. This causes less work for both humans and computers to do when reading code, and creates more optimization opportunities.
{#header_open|Identifiers#}Variable identifiers are never allowed to shadow identifiers from an outer scope.
Identifiers must start with an alphabetic character or underscore and may be followed by any number of alphanumeric characters or underscores. They must not overlap with any keywords. See {#link|Keyword Reference#}.
If a name that does not fit these requirements is needed, such as for linking with external libraries, the {#syntax#}@""{#endsyntax#} syntax may be used.
{#code_begin|syntax#} const @"identifier with spaces in it" = 0xff; const @"1SmallStep4Man" = 112358; const c = @import("std").c; pub extern "c" fn @"error"() void; pub extern "c" fn @"fstat$INODE64"(fd: c.fd_t, buf: *c.Stat) c_int; const Color = enum { red, @"really red", }; const color: Color = .@"really red"; {#code_end#} {#header_close#} {#header_open|Container Level Variables#}{#link|Container|Containers#} level variables have static lifetime and are order-independent and lazily analyzed. The initialization value of container level variables is implicitly {#link|comptime#}. If a container level variable is {#syntax#}const{#endsyntax#} then its value is {#syntax#}comptime{#endsyntax#}-known, otherwise it is runtime-known.
{#code_begin|test|container_level_variables#} var y: i32 = add(10, x); const x: i32 = add(12, 34); test "container level variables" { try expect(x == 46); try expect(y == 56); } fn add(a: i32, b: i32) i32 { return a + b; } const std = @import("std"); const expect = std.testing.expect; {#code_end#}Container level variables may be declared inside a {#link|struct#}, {#link|union#}, {#link|enum#}, or {#link|opaque#}:
{#code_begin|test|namespaced_container_level_variable#} const std = @import("std"); const expect = std.testing.expect; test "namespaced container level variable" { try expect(foo() == 1235); try expect(foo() == 1236); } const S = struct { var x: i32 = 1234; }; fn foo() i32 { S.x += 1; return S.x; } {#code_end#} {#header_close#} {#header_open|Static Local Variables#}It is also possible to have local variables with static lifetime by using containers inside functions.
{#code_begin|test|static_local_variable#} const std = @import("std"); const expect = std.testing.expect; test "static local variable" { try expect(foo() == 1235); try expect(foo() == 1236); } fn foo() i32 { const S = struct { var x: i32 = 1234; }; S.x += 1; return S.x; } {#code_end#}The {#syntax#}extern{#endsyntax#} keyword or {#link|@extern#} builtin function can be used to link against a variable that is exported from another object. The {#syntax#}export{#endsyntax#} keyword or {#link|@export#} builtin function can be used to make a variable available to other objects at link time. In both cases, the type of the variable must be C ABI compatible.
{#see_also|Exporting a C Library#} {#header_close#} {#header_open|Thread Local Variables#}A variable may be specified to be a thread-local variable using the {#syntax#}threadlocal{#endsyntax#} keyword:
{#code_begin|test|tls#} const std = @import("std"); const assert = std.debug.assert; threadlocal var x: i32 = 1234; test "thread local storage" { const thread1 = try std.Thread.spawn(.{}, testTls, .{}); const thread2 = try std.Thread.spawn(.{}, testTls, .{}); testTls(); thread1.join(); thread2.join(); } fn testTls() void { assert(x == 1234); x += 1; assert(x == 1235); } {#code_end#}For {#link|Single Threaded Builds#}, all thread local variables are treated as regular {#link|Container Level Variables#}.
Thread local variables may not be {#syntax#}const{#endsyntax#}.
{#header_close#} {#header_open|Local Variables#}Local variables occur inside {#link|Functions#}, {#link|comptime#} blocks, and {#link|@cImport#} blocks.
When a local variable is {#syntax#}const{#endsyntax#}, it means that after initialization, the variable's value will not change. If the initialization value of a {#syntax#}const{#endsyntax#} variable is {#link|comptime#}-known, then the variable is also {#syntax#}comptime{#endsyntax#}-known.
A local variable may be qualified with the {#syntax#}comptime{#endsyntax#} keyword. This causes the variable's value to be {#syntax#}comptime{#endsyntax#}-known, and all loads and stores of the variable to happen during semantic analysis of the program, rather than at runtime. All variables declared in a {#syntax#}comptime{#endsyntax#} expression are implicitly {#syntax#}comptime{#endsyntax#} variables.
{#code_begin|test|comptime_vars#} const std = @import("std"); const expect = std.testing.expect; test "comptime vars" { var x: i32 = 1; comptime var y: i32 = 1; x += 1; y += 1; try expect(x == 2); try expect(y == 2); if (y != 2) { // This compile error never triggers because y is a comptime variable, // and so `y != 2` is a comptime value, and this if is statically evaluated. @compileError("wrong y value"); } } {#code_end#} {#header_close#} {#header_close#} {#header_open|Integers#} {#header_open|Integer Literals#} {#code_begin|syntax|integer_literals#} const decimal_int = 98222; const hex_int = 0xff; const another_hex_int = 0xFF; const octal_int = 0o755; const binary_int = 0b11110000; // underscores may be placed between two digits as a visual separator const one_billion = 1_000_000_000; const binary_mask = 0b1_1111_1111; const permissions = 0o7_5_5; const big_address = 0xFF80_0000_0000_0000; {#code_end#} {#header_close#} {#header_open|Runtime Integer Values#}Integer literals have no size limitation, and if any undefined behavior occurs, the compiler catches it.
However, once an integer value is no longer known at compile-time, it must have a known size, and is vulnerable to undefined behavior.
{#code_begin|syntax|runtime_vs_comptime#} fn divide(a: i32, b: i32) i32 { return a / b; } {#code_end#}In this function, values {#syntax#}a{#endsyntax#} and {#syntax#}b{#endsyntax#} are known only at runtime, and thus this division operation is vulnerable to both {#link|Integer Overflow#} and {#link|Division by Zero#}.
Operators such as {#syntax#}+{#endsyntax#} and {#syntax#}-{#endsyntax#} cause undefined behavior on integer overflow. Alternative operators are provided for wrapping and saturating arithmetic on all targets. {#syntax#}+%{#endsyntax#} and {#syntax#}-%{#endsyntax#} perform wrapping arithmetic while {#syntax#}+|{#endsyntax#} and {#syntax#}-|{#endsyntax#} perform saturating arithmetic.
Zig supports arbitrary bit-width integers, referenced by using
an identifier of i
or u
followed by digits. For example, the identifier
{#syntax#}i7{#endsyntax#} refers to a signed 7-bit integer. The maximum allowed bit-width of an
integer type is {#syntax#}65535{#endsyntax#}. For signed integer types, Zig uses a
two's complement representation.
Zig has the following floating point types:
- {#syntax#}f16{#endsyntax#} - IEEE-754-2008 binary16
- {#syntax#}f32{#endsyntax#} - IEEE-754-2008 binary32
- {#syntax#}f64{#endsyntax#} - IEEE-754-2008 binary64
- {#syntax#}f80{#endsyntax#} - IEEE-754-2008 80-bit extended precision
- {#syntax#}f128{#endsyntax#} - IEEE-754-2008 binary128
- {#syntax#}c_longdouble{#endsyntax#} - matches
long double
for the target C ABI
Float literals have type {#syntax#}comptime_float{#endsyntax#} which is guaranteed to have the same precision and operations of the largest other floating point type, which is {#syntax#}f128{#endsyntax#}.
Float literals {#link|coerce|Type Coercion#} to any floating point type, and to any {#link|integer|Integers#} type when there is no fractional component.
{#code_begin|syntax|float_literals#} const floating_point = 123.0E+77; const another_float = 123.0; const yet_another = 123.0e+77; const hex_floating_point = 0x103.70p-5; const another_hex_float = 0x103.70; const yet_another_hex_float = 0x103.70P-5; // underscores may be placed between two digits as a visual separator const lightspeed = 299_792_458.000_000; const nanosecond = 0.000_000_001; const more_hex = 0x1234_5678.9ABC_CDEFp-10; {#code_end#}There is no syntax for NaN, infinity, or negative infinity. For these special values, one must use the standard library:
{#code_begin|syntax|float_special_values#} const std = @import("std"); const inf = std.math.inf(f32); const negative_inf = -std.math.inf(f64); const nan = std.math.nan(f128); {#code_end#} {#header_close#} {#header_open|Floating Point Operations#}By default floating point operations use {#syntax#}Strict{#endsyntax#} mode, but you can switch to {#syntax#}Optimized{#endsyntax#} mode on a per-block basis:
{#code_begin|obj|foo#} {#code_release_fast#} {#code_disable_cache#} const std = @import("std"); const big = @as(f64, 1 << 40); export fn foo_strict(x: f64) f64 { return x + big - big; } export fn foo_optimized(x: f64) f64 { @setFloatMode(.Optimized); return x + big - big; } {#code_end#}For this test we have to separate code into two object files - otherwise the optimizer figures out all the values at compile-time, which operates in strict mode.
{#code_begin|exe|float_mode#} {#code_link_object|foo#} const print = @import("std").debug.print; extern fn foo_strict(x: f64) f64; extern fn foo_optimized(x: f64) f64; pub fn main() void { const x = 0.001; print("optimized = {}\n", .{foo_optimized(x)}); print("strict = {}\n", .{foo_strict(x)}); } {#code_end#} {#see_also|@setFloatMode|Division by Zero#} {#header_close#} {#header_close#} {#header_open|Operators#}There is no operator overloading. When you see an operator in Zig, you know that it is doing something from this table, and nothing else.
{#header_open|Table of Operators#}Syntax | Relevant Types | Description | Example |
---|---|---|---|
{#syntax#}a + b a += b{#endsyntax#} |
|
Addition.
|
{#syntax#}2 + 5 == 7{#endsyntax#} |
{#syntax#}a +% b a +%= b{#endsyntax#} |
|
Wrapping Addition.
|
{#syntax#}@as(u32, std.math.maxInt(u32)) +% 1 == 0{#endsyntax#} |
{#syntax#}a +| b a +|= b{#endsyntax#} |
|
Saturating Addition.
|
{#syntax#}@as(u32, std.math.maxInt(u32)) +| 1 == @as(u32, std.math.maxInt(u32)){#endsyntax#} |
{#syntax#}a - b a -= b{#endsyntax#} |
|
Subtraction.
|
{#syntax#}2 - 5 == -3{#endsyntax#} |
{#syntax#}a -% b a -%= b{#endsyntax#} |
|
Wrapping Subtraction.
|
{#syntax#}@as(u32, 0) -% 1 == std.math.maxInt(u32){#endsyntax#} |
{#syntax#}a -| b a -|= b{#endsyntax#} |
|
Saturating Subtraction.
|
{#syntax#}@as(u32, 0) -| 1 == 0{#endsyntax#} |
{#syntax#}-a{#endsyntax#} |
|
Negation.
|
{#syntax#}-1 == 0 - 1{#endsyntax#} |
{#syntax#}-%a{#endsyntax#} |
|
Wrapping Negation.
|
{#syntax#}-%@as(i32, std.math.minInt(i32)) == std.math.minInt(i32){#endsyntax#} |
{#syntax#}a * b a *= b{#endsyntax#} |
|
Multiplication.
|
{#syntax#}2 * 5 == 10{#endsyntax#} |
{#syntax#}a *% b a *%= b{#endsyntax#} |
|
Wrapping Multiplication.
|
{#syntax#}@as(u8, 200) *% 2 == 144{#endsyntax#} |
{#syntax#}a *| b a *|= b{#endsyntax#} |
|
Saturating Multiplication.
|
{#syntax#}@as(u8, 200) *| 2 == 255{#endsyntax#} |
{#syntax#}a / b a /= b{#endsyntax#} |
|
Division.
|
{#syntax#}10 / 5 == 2{#endsyntax#} |
{#syntax#}a % b a %= b{#endsyntax#} |
|
Remainder Division.
|
{#syntax#}10 % 3 == 1{#endsyntax#} |
{#syntax#}a << b a <<= b{#endsyntax#} |
|
Bit Shift Left.
|
{#syntax#}1 << 8 == 256{#endsyntax#} |
{#syntax#}a <<| b a <<|= b{#endsyntax#} |
|
Saturating Bit Shift Left.
|
{#syntax#}@as(u8, 1) <<| 8 == 255{#endsyntax#} |
{#syntax#}a >> b a >>= b{#endsyntax#} |
|
Bit Shift Right.
|
{#syntax#}10 >> 1 == 5{#endsyntax#} |
{#syntax#}a & b a &= b{#endsyntax#} |
|
Bitwise AND.
|
{#syntax#}0b011 & 0b101 == 0b001{#endsyntax#} |
{#syntax#}a | b a |= b{#endsyntax#} |
|
Bitwise OR.
|
{#syntax#}0b010 | 0b100 == 0b110{#endsyntax#} |
{#syntax#}a ^ b a ^= b{#endsyntax#} |
|
Bitwise XOR.
|
{#syntax#}0b011 ^ 0b101 == 0b110{#endsyntax#} |
{#syntax#}~a{#endsyntax#} |
|
Bitwise NOT. |
{#syntax#}~@as(u8, 0b10101111) == 0b01010000{#endsyntax#} |
{#syntax#}a orelse b{#endsyntax#} |
|
If {#syntax#}a{#endsyntax#} is {#syntax#}null{#endsyntax#}, returns {#syntax#}b{#endsyntax#} ("default value"), otherwise returns the unwrapped value of {#syntax#}a{#endsyntax#}. Note that {#syntax#}b{#endsyntax#} may be a value of type {#link|noreturn#}. |
{#syntax#}const value: ?u32 = null; const unwrapped = value orelse 1234; unwrapped == 1234{#endsyntax#} |
{#syntax#}a.?{#endsyntax#} |
|
Equivalent to:
{#syntax#}a orelse unreachable{#endsyntax#} |
{#syntax#}const value: ?u32 = 5678; value.? == 5678{#endsyntax#} |
{#syntax#}a catch b a catch |err| b{#endsyntax#} |
|
If {#syntax#}a{#endsyntax#} is an {#syntax#}error{#endsyntax#}, returns {#syntax#}b{#endsyntax#} ("default value"), otherwise returns the unwrapped value of {#syntax#}a{#endsyntax#}. Note that {#syntax#}b{#endsyntax#} may be a value of type {#link|noreturn#}. {#syntax#}err{#endsyntax#} is the {#syntax#}error{#endsyntax#} and is in scope of the expression {#syntax#}b{#endsyntax#}. |
{#syntax#}const value: anyerror!u32 = error.Broken; const unwrapped = value catch 1234; unwrapped == 1234{#endsyntax#} |
{#syntax#}a and b{#endsyntax#} |
|
If {#syntax#}a{#endsyntax#} is {#syntax#}false{#endsyntax#}, returns {#syntax#}false{#endsyntax#} without evaluating {#syntax#}b{#endsyntax#}. Otherwise, returns {#syntax#}b{#endsyntax#}. |
{#syntax#}(false and true) == false{#endsyntax#} |
{#syntax#}a or b{#endsyntax#} |
|
If {#syntax#}a{#endsyntax#} is {#syntax#}true{#endsyntax#}, returns {#syntax#}true{#endsyntax#} without evaluating {#syntax#}b{#endsyntax#}. Otherwise, returns {#syntax#}b{#endsyntax#}. |
{#syntax#}(false or true) == true{#endsyntax#} |
{#syntax#}!a{#endsyntax#} |
|
Boolean NOT. |
{#syntax#}!false == true{#endsyntax#} |
{#syntax#}a == b{#endsyntax#} |
|
Returns {#syntax#}true{#endsyntax#} if a and b are equal, otherwise returns {#syntax#}false{#endsyntax#}. Invokes {#link|Peer Type Resolution#} for the operands. |
{#syntax#}(1 == 1) == true{#endsyntax#} |
{#syntax#}a == null{#endsyntax#} |
|
Returns {#syntax#}true{#endsyntax#} if a is {#syntax#}null{#endsyntax#}, otherwise returns {#syntax#}false{#endsyntax#}. |
{#syntax#}const value: ?u32 = null; value == null{#endsyntax#} |
{#syntax#}a != b{#endsyntax#} |
|
Returns {#syntax#}false{#endsyntax#} if a and b are equal, otherwise returns {#syntax#}true{#endsyntax#}. Invokes {#link|Peer Type Resolution#} for the operands. |
{#syntax#}(1 != 1) == false{#endsyntax#} |
{#syntax#}a > b{#endsyntax#} |
|
Returns {#syntax#}true{#endsyntax#} if a is greater than b, otherwise returns {#syntax#}false{#endsyntax#}. Invokes {#link|Peer Type Resolution#} for the operands. |
{#syntax#}(2 > 1) == true{#endsyntax#} |
{#syntax#}a >= b{#endsyntax#} |
|
Returns {#syntax#}true{#endsyntax#} if a is greater than or equal to b, otherwise returns {#syntax#}false{#endsyntax#}. Invokes {#link|Peer Type Resolution#} for the operands. |
{#syntax#}(2 >= 1) == true{#endsyntax#} |
{#syntax#}a < b{#endsyntax#} |
|
Returns {#syntax#}true{#endsyntax#} if a is less than b, otherwise returns {#syntax#}false{#endsyntax#}. Invokes {#link|Peer Type Resolution#} for the operands. |
{#syntax#}(1 < 2) == true{#endsyntax#}> |
{#syntax#}a <= b{#endsyntax#} |
|
Returns {#syntax#}true{#endsyntax#} if a is less than or equal to b, otherwise returns {#syntax#}false{#endsyntax#}. Invokes {#link|Peer Type Resolution#} for the operands. |
{#syntax#}(1 <= 2) == true{#endsyntax#} |
{#syntax#}a ++ b{#endsyntax#} |
|
Array concatenation.
|
{#syntax#}const mem = @import("std").mem; const array1 = [_]u32{1,2}; const array2 = [_]u32{3,4}; const together = array1 ++ array2; mem.eql(u32, &together, &[_]u32{1,2,3,4}){#endsyntax#} |
{#syntax#}a ** b{#endsyntax#} |
|
Array multiplication.
|
{#syntax#}const mem = @import("std").mem; const pattern = "ab" ** 3; mem.eql(u8, pattern, "ababab"){#endsyntax#} |
{#syntax#}a.*{#endsyntax#} |
|
Pointer dereference. |
{#syntax#}const x: u32 = 1234; const ptr = &x; ptr.* == 1234{#endsyntax#} |
{#syntax#}&a{#endsyntax#} |
All types | Address of. |
{#syntax#}const x: u32 = 1234; const ptr = &x; ptr.* == 1234{#endsyntax#} |
{#syntax#}a || b{#endsyntax#} |
|
{#link|Merging Error Sets#} |
{#syntax#}const A = error{One}; const B = error{Two}; (A || B) == error{One, Two}{#endsyntax#} |
{#syntax#}x() x[] x.y x.* x.? a!b x{} !x -x -%x ~x &x ?x * / % ** *% *| || + - ++ +% -% +| -| << >> <<| & ^ | orelse catch == != < > <= >= and or = *= *%= *|= /= %= += +%= +|= -= -%= -|= <<= <<|= >>= &= ^= |={#endsyntax#}{#header_close#} {#header_close#} {#header_open|Arrays#} {#code_begin|test|arrays#} const expect = @import("std").testing.expect; const assert = @import("std").debug.assert; const mem = @import("std").mem; // array literal const message = [_]u8{ 'h', 'e', 'l', 'l', 'o' }; // get the size of an array comptime { assert(message.len == 5); } // A string literal is a single-item pointer to an array literal. const same_message = "hello"; comptime { assert(mem.eql(u8, &message, same_message)); } test "iterate over an array" { var sum: usize = 0; for (message) |byte| { sum += byte; } try expect(sum == 'h' + 'e' + 'l' * 2 + 'o'); } // modifiable array var some_integers: [100]i32 = undefined; test "modify an array" { for (some_integers) |*item, i| { item.* = @intCast(i32, i); } try expect(some_integers[10] == 10); try expect(some_integers[99] == 99); } // array concatenation works if the values are known // at compile time const part_one = [_]i32{ 1, 2, 3, 4 }; const part_two = [_]i32{ 5, 6, 7, 8 }; const all_of_it = part_one ++ part_two; comptime { assert(mem.eql(i32, &all_of_it, &[_]i32{ 1, 2, 3, 4, 5, 6, 7, 8 })); } // remember that string literals are arrays const hello = "hello"; const world = "world"; const hello_world = hello ++ " " ++ world; comptime { assert(mem.eql(u8, hello_world, "hello world")); } // ** does repeating patterns const pattern = "ab" ** 3; comptime { assert(mem.eql(u8, pattern, "ababab")); } // initialize an array to zero const all_zero = [_]u16{0} ** 10; comptime { assert(all_zero.len == 10); assert(all_zero[5] == 0); } // use compile-time code to initialize an array var fancy_array = init: { var initial_value: [10]Point = undefined; for (initial_value) |*pt, i| { pt.* = Point{ .x = @intCast(i32, i), .y = @intCast(i32, i) * 2, }; } break :init initial_value; }; const Point = struct { x: i32, y: i32, }; test "compile-time array initialization" { try expect(fancy_array[4].x == 4); try expect(fancy_array[4].y == 8); } // call a function to initialize an array var more_points = [_]Point{makePoint(3)} ** 10; fn makePoint(x: i32) Point { return Point{ .x = x, .y = x * 2, }; } test "array initialization with function calls" { try expect(more_points[4].x == 3); try expect(more_points[4].y == 6); try expect(more_points.len == 10); } {#code_end#} {#see_also|for|Slices#} {#header_open|Anonymous List Literals#}
Similar to {#link|Enum Literals#} and {#link|Anonymous Struct Literals#} the type can be omitted from array literals:
{#code_begin|test|anon_list#} const std = @import("std"); const expect = std.testing.expect; test "anonymous list literal syntax" { var array: [4]u8 = .{11, 22, 33, 44}; try expect(array[0] == 11); try expect(array[1] == 22); try expect(array[2] == 33); try expect(array[3] == 44); } {#code_end#}If there is no type in the result location then an anonymous list literal actually turns into a {#link|struct#} with numbered field names:
{#code_begin|test|infer_list_literal#} const std = @import("std"); const expect = std.testing.expect; test "fully anonymous list literal" { try dump(.{ @as(u32, 1234), @as(f64, 12.34), true, "hi"}); } fn dump(args: anytype) !void { try expect(args.@"0" == 1234); try expect(args.@"1" == 12.34); try expect(args.@"2"); try expect(args.@"3"[0] == 'h'); try expect(args.@"3"[1] == 'i'); } {#code_end#} {#header_close#} {#header_open|Multidimensional Arrays#}Multidimensional arrays can be created by nesting arrays:
{#code_begin|test|multidimensional#} const std = @import("std"); const expect = std.testing.expect; const mat4x4 = [4][4]f32{ [_]f32{ 1.0, 0.0, 0.0, 0.0 }, [_]f32{ 0.0, 1.0, 0.0, 1.0 }, [_]f32{ 0.0, 0.0, 1.0, 0.0 }, [_]f32{ 0.0, 0.0, 0.0, 1.0 }, }; test "multidimensional arrays" { // Access the 2D array by indexing the outer array, and then the inner array. try expect(mat4x4[1][1] == 1.0); // Here we iterate with for loops. for (mat4x4) |row, row_index| { for (row) |cell, column_index| { if (row_index == column_index) { try expect(cell == 1.0); } } } } {#code_end#} {#header_close#} {#header_open|Sentinel-Terminated Arrays#}The syntax {#syntax#}[N:x]T{#endsyntax#} describes an array which has a sentinel element of value {#syntax#}x{#endsyntax#} at the index corresponding to {#syntax#}len{#endsyntax#}.
{#code_begin|test|null_terminated_array#} const std = @import("std"); const expect = std.testing.expect; test "null terminated array" { const array = [_:0]u8 {1, 2, 3, 4}; try expect(@TypeOf(array) == [4:0]u8); try expect(array.len == 4); try expect(array[4] == 0); } {#code_end#} {#see_also|Sentinel-Terminated Pointers|Sentinel-Terminated Slices#} {#header_close#} {#header_close#} {#header_open|Vectors#}A vector is a group of booleans, {#link|Integers#}, {#link|Floats#}, or {#link|Pointers#} which are operated on in parallel, using SIMD instructions if possible. Vector types are created with the builtin function {#link|@Vector#}.
Vectors support the same builtin operators as their underlying base types. These operations are performed element-wise, and return a vector of the same length as the input vectors. This includes:
- Arithmetic ({#syntax#}+{#endsyntax#}, {#syntax#}-{#endsyntax#}, {#syntax#}/{#endsyntax#}, {#syntax#}*{#endsyntax#}, {#syntax#}@divFloor{#endsyntax#}, {#syntax#}@sqrt{#endsyntax#}, {#syntax#}@ceil{#endsyntax#}, {#syntax#}@log{#endsyntax#}, etc.)
- Bitwise operators ({#syntax#}>>{#endsyntax#}, {#syntax#}<<{#endsyntax#}, {#syntax#}&{#endsyntax#}, {#syntax#}|{#endsyntax#}, {#syntax#}~{#endsyntax#}, etc.)
- Comparison operators ({#syntax#}<{#endsyntax#}, {#syntax#}>{#endsyntax#}, {#syntax#}=={#endsyntax#}, etc.)
It is prohibited to use a math operator on a mixture of scalars (individual numbers) and vectors. Zig provides the {#link|@splat#} builtin to easily convert from scalars to vectors, and it supports {#link|@reduce#} and array indexing syntax to convert from vectors to scalars. Vectors also support assignment to and from fixed-length arrays with comptime known length.
For rearranging elements within and between vectors, Zig provides the {#link|@shuffle#} and {#link|@select#} functions.
Operations on vectors shorter than the target machine's native SIMD size will typically compile to single SIMD instructions, while vectors longer than the target machine's native SIMD size will compile to multiple SIMD instructions. If a given operation doesn't have SIMD support on the target architecture, the compiler will default to operating on each vector element one at a time. Zig supports any comptime-known vector length up to 2^32-1, although small powers of two (2-64) are most typical. Note that excessively long vector lengths (e.g. 2^20) may result in compiler crashes on current versions of Zig.
{#code_begin|test|vector_example#} const std = @import("std"); const expectEqual = std.testing.expectEqual; test "Basic vector usage" { // Vectors have a compile-time known length and base type. const a = @Vector(4, i32){ 1, 2, 3, 4 }; const b = @Vector(4, i32){ 5, 6, 7, 8 }; // Math operations take place element-wise. const c = a + b; // Individual vector elements can be accessed using array indexing syntax. try expectEqual(6, c[0]); try expectEqual(8, c[1]); try expectEqual(10, c[2]); try expectEqual(12, c[3]); } test "Conversion between vectors, arrays, and slices" { // Vectors and fixed-length arrays can be automatically assigned back and forth var arr1: [4]f32 = [_]f32{ 1.1, 3.2, 4.5, 5.6 }; var vec: @Vector(4, f32) = arr1; var arr2: [4]f32 = vec; try expectEqual(arr1, arr2); // You can also assign from a slice with comptime-known length to a vector using .* const vec2: @Vector(2, f32) = arr1[1..3].*; var slice: []const f32 = &arr1; var offset: u32 = 1; // To extract a comptime-known length from a runtime-known offset, // first extract a new slice from the starting offset, then an array of // comptime known length const vec3: @Vector(2, f32) = slice[offset..][0..2].*; try expectEqual(slice[offset], vec2[0]); try expectEqual(slice[offset + 1], vec2[1]); try expectEqual(vec2, vec3); } {#code_end#}
TODO talk about C ABI interop
TODO consider suggesting std.MultiArrayList
Zig has two kinds of pointers: single-item and many-item.
- {#syntax#}*T{#endsyntax#} - single-item pointer to exactly one item.
- Supports deref syntax: {#syntax#}ptr.*{#endsyntax#}
- {#syntax#}[*]T{#endsyntax#} - many-item pointer to unknown number of items.
- Supports index syntax: {#syntax#}ptr[i]{#endsyntax#}
- Supports slice syntax: {#syntax#}ptr[start..end]{#endsyntax#}
- Supports pointer arithmetic: {#syntax#}ptr + x{#endsyntax#}, {#syntax#}ptr - x{#endsyntax#}
- {#syntax#}T{#endsyntax#} must have a known size, which means that it cannot be {#syntax#}anyopaque{#endsyntax#} or any other {#link|opaque type|opaque#}.
These types are closely related to {#link|Arrays#} and {#link|Slices#}:
- {#syntax#}*[N]T{#endsyntax#} - pointer to N items, same as single-item pointer to an array.
- Supports index syntax: {#syntax#}array_ptr[i]{#endsyntax#}
- Supports slice syntax: {#syntax#}array_ptr[start..end]{#endsyntax#}
- Supports len property: {#syntax#}array_ptr.len{#endsyntax#}
- {#syntax#}[]T{#endsyntax#} - is a slice (a fat pointer, which contains a pointer of type {#syntax#}[*]T{#endsyntax#} and a length).
- Supports index syntax: {#syntax#}slice[i]{#endsyntax#}
- Supports slice syntax: {#syntax#}slice[start..end]{#endsyntax#}
- Supports len property: {#syntax#}slice.len{#endsyntax#}
Use {#syntax#}&x{#endsyntax#} to obtain a single-item pointer:
{#code_begin|test|single_item_pointer_test#} const expect = @import("std").testing.expect; test "address of syntax" { // Get the address of a variable: const x: i32 = 1234; const x_ptr = &x; // Dereference a pointer: try expect(x_ptr.* == 1234); // When you get the address of a const variable, you get a const single-item pointer. try expect(@TypeOf(x_ptr) == *const i32); // If you want to mutate the value, you'd need an address of a mutable variable: var y: i32 = 5678; const y_ptr = &y; try expect(@TypeOf(y_ptr) == *i32); y_ptr.* += 1; try expect(y_ptr.* == 5679); } test "pointer array access" { // Taking an address of an individual element gives a // single-item pointer. This kind of pointer // does not support pointer arithmetic. var array = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; const ptr = &array[2]; try expect(@TypeOf(ptr) == *u8); try expect(array[2] == 3); ptr.* += 1; try expect(array[2] == 4); } {#code_end#}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.
{#code_begin|test|pointer_arthemtic#} const expect = @import("std").testing.expect; test "pointer arithmetic with many-item pointer" { const array = [_]i32{ 1, 2, 3, 4 }; var ptr: [*]const i32 = &array; try expect(ptr[0] == 1); ptr += 1; try expect(ptr[0] == 2); } test "pointer arithmetic with slices" { var array = [_]i32{ 1, 2, 3, 4 }; var length: usize = 0; var slice = array[length..array.len]; try expect(slice[0] == 1); try expect(slice.len == 4); slice.ptr += 1; // now the slice is in an bad state since len has not been updated try expect(slice[0] == 2); try expect(slice.len == 4); } {#code_end#}In Zig, we generally prefer {#link|Slices#} rather than {#link|Sentinel-Terminated Pointers#}. You can turn an array or pointer into a slice using slice syntax.
Slices have bounds checking and are therefore protected against this kind of undefined behavior. This is one reason we prefer slices to pointers.
{#code_begin|test|slice_bounds#} const expect = @import("std").testing.expect; test "pointer slicing" { var array = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; const slice = array[2..4]; try expect(slice.len == 2); try expect(array[3] == 4); slice[1] += 1; try expect(array[3] == 5); } {#code_end#}Pointers work at compile-time too, as long as the code does not depend on an undefined memory layout:
{#code_begin|test|comptime_pointers#} const expect = @import("std").testing.expect; test "comptime pointers" { comptime { var x: i32 = 1; const ptr = &x; ptr.* += 1; x += 1; try expect(ptr.* == 3); } } {#code_end#}To convert an integer address into a pointer, use {#syntax#}@intToPtr{#endsyntax#}. To convert a pointer to an integer, use {#syntax#}@ptrToInt{#endsyntax#}:
{#code_begin|test|integer_pointer_conversion#} const expect = @import("std").testing.expect; test "@ptrToInt and @intToPtr" { const ptr = @intToPtr(*i32, 0xdeadbee0); const addr = @ptrToInt(ptr); try expect(@TypeOf(addr) == usize); try expect(addr == 0xdeadbee0); } {#code_end#}Zig is able to preserve memory addresses in comptime code, as long as the pointer is never dereferenced:
{#code_begin|test|comptime_pointer_conversion#} const expect = @import("std").testing.expect; test "comptime @intToPtr" { comptime { // Zig is able to do this at compile-time, as long as // ptr is never dereferenced. const ptr = @intToPtr(*i32, 0xdeadbee0); const addr = @ptrToInt(ptr); try expect(@TypeOf(addr) == usize); try expect(addr == 0xdeadbee0); } } {#code_end#} {#see_also|Optional Pointers|@intToPtr|@ptrToInt|C Pointers#} {#header_open|volatile#}Loads and stores are assumed to not have side effects. If a given load or store should have side effects, such as Memory Mapped Input/Output (MMIO), use {#syntax#}volatile{#endsyntax#}. In the following code, loads and stores with {#syntax#}mmio_ptr{#endsyntax#} are guaranteed to all happen and in the same order as in source code:
{#code_begin|test|volatile#} const expect = @import("std").testing.expect; test "volatile" { const mmio_ptr = @intToPtr(*volatile u8, 0x12345678); try expect(@TypeOf(mmio_ptr) == *volatile u8); } {#code_end#}Note that {#syntax#}volatile{#endsyntax#} is unrelated to concurrency and {#link|Atomics#}. If you see code that is using {#syntax#}volatile{#endsyntax#} for something other than Memory Mapped Input/Output, it is probably a bug.
{#header_close#}To convert one pointer type to another, use {#link|@ptrCast#}. This is an unsafe operation that Zig cannot protect you against. Use {#syntax#}@ptrCast{#endsyntax#} only when other conversions are not possible.
{#code_begin|test|pointer_casting#} const std = @import("std"); const expect = std.testing.expect; test "pointer casting" { const bytes align(@alignOf(u32)) = [_]u8{ 0x12, 0x12, 0x12, 0x12 }; const u32_ptr = @ptrCast(*const u32, &bytes); try expect(u32_ptr.* == 0x12121212); // Even this example is contrived - there are better ways to do the above than // pointer casting. For example, using a slice narrowing cast: const u32_value = std.mem.bytesAsSlice(u32, bytes[0..])[0]; try expect(u32_value == 0x12121212); // And even another way, the most straightforward way to do it: try expect(@bitCast(u32, bytes) == 0x12121212); } test "pointer child type" { // pointer types have a `child` field which tells you the type they point to. try expect(@typeInfo(*u32).Pointer.child == u32); } {#code_end#} {#header_open|Alignment#}Each type has an alignment - a number of bytes such that, when a value of the type is loaded from or stored to memory, the memory address must be evenly divisible by this number. You can use {#link|@alignOf#} to find out this value for any type.
Alignment depends on the CPU architecture, but is always a power of two, and less than {#syntax#}1 << 29{#endsyntax#}.
In Zig, a pointer type has an alignment value. If the value is equal to the alignment of the underlying type, it can be omitted from the type:
{#code_begin|test|variable_alignment#} const std = @import("std"); const builtin = @import("builtin"); const expect = std.testing.expect; test "variable alignment" { var x: i32 = 1234; const align_of_i32 = @alignOf(@TypeOf(x)); try expect(@TypeOf(&x) == *i32); try expect(*i32 == *align(align_of_i32) i32); if (builtin.target.cpu.arch == .x86_64) { try expect(@typeInfo(*i32).Pointer.alignment == 4); } } {#code_end#}In the same way that a {#syntax#}*i32{#endsyntax#} can be {#link|coerced|Type Coercion#} to a {#syntax#}*const i32{#endsyntax#}, a pointer with a larger alignment can be implicitly cast to a pointer with a smaller alignment, but not vice versa.
You can specify alignment on variables and functions. If you do this, then pointers to them get the specified alignment:
{#code_begin|test|variable_func_alignment#} const expect = @import("std").testing.expect; var foo: u8 align(4) = 100; test "global variable alignment" { try expect(@typeInfo(@TypeOf(&foo)).Pointer.alignment == 4); try expect(@TypeOf(&foo) == *align(4) u8); const as_pointer_to_array: *align(4) [1]u8 = &foo; const as_slice: []align(4) u8 = as_pointer_to_array; const as_unaligned_slice: []u8 = as_slice; try expect(as_unaligned_slice[0] == 100); } fn derp() align(@sizeOf(usize) * 2) i32 { return 1234; } fn noop1() align(1) void {} fn noop4() align(4) void {} test "function alignment" { try expect(derp() == 1234); try expect(@TypeOf(noop1) == fn () align(1) void); try expect(@TypeOf(noop4) == fn () align(4) void); noop1(); noop4(); } {#code_end#}If you have a pointer or a slice that has a small alignment, but you know that it actually has a bigger alignment, use {#link|@alignCast#} to change the pointer into a more aligned pointer. This is a no-op at runtime, but inserts a {#link|safety check|Incorrect Pointer Alignment#}:
{#code_begin|test_safety|incorrect alignment#} const std = @import("std"); test "pointer alignment safety" { var array align(4) = [_]u32{ 0x11111111, 0x11111111 }; const bytes = std.mem.sliceAsBytes(array[0..]); try std.testing.expect(foo(bytes) == 0x11111111); } fn foo(bytes: []u8) u32 { const slice4 = bytes[1..5]; const int_slice = std.mem.bytesAsSlice(u32, @alignCast(4, slice4)); return int_slice[0]; } {#code_end#} {#header_close#} {#header_open|allowzero#}This pointer attribute allows a pointer to have address zero. This is only ever needed on the freestanding OS target, where the address zero is mappable. If you want to represent null pointers, use {#link|Optional Pointers#} instead. {#link|Optional Pointers#} with {#syntax#}allowzero{#endsyntax#} are not the same size as pointers. In this code example, if the pointer did not have the {#syntax#}allowzero{#endsyntax#} attribute, this would be a {#link|Pointer Cast Invalid Null#} panic:
{#code_begin|test|allowzero#} const std = @import("std"); const expect = std.testing.expect; test "allowzero" { var zero: usize = 0; var ptr = @intToPtr(*allowzero i32, zero); try expect(@ptrToInt(ptr) == 0); } {#code_end#} {#header_close#} {#header_open|Sentinel-Terminated Pointers#}The syntax {#syntax#}[*:x]T{#endsyntax#} describes a pointer that has a length determined by a sentinel value. This provides protection against buffer overflow and overreads.
{#code_begin|exe_build_err#} {#link_libc#} const std = @import("std"); // This is also available as `std.c.printf`. pub extern "c" fn printf(format: [*:0]const u8, ...) c_int; pub fn main() anyerror!void { _ = printf("Hello, world!\n"); // OK const msg = "Hello, world!\n"; const non_null_terminated_msg: [msg.len]u8 = msg.*; _ = printf(&non_null_terminated_msg); } {#code_end#} {#see_also|Sentinel-Terminated Slices|Sentinel-Terminated Arrays#} {#header_close#} {#header_close#} {#header_open|Slices#} {#code_begin|test_safety|index out of bounds#} const expect = @import("std").testing.expect; test "basic slices" { var array = [_]i32{ 1, 2, 3, 4 }; // A slice is a pointer and a length. The difference between an array and // a slice is that the array's length is part of the type and known at // compile-time, whereas the slice's length is known at runtime. // Both can be accessed with the `len` field. var known_at_runtime_zero: usize = 0; const slice = array[known_at_runtime_zero..array.len]; try expect(@TypeOf(slice) == []i32); try expect(&slice[0] == &array[0]); try expect(slice.len == array.len); // If you slice with comptime-known start and end positions, the result is // a pointer to an array, rather than a slice. const array_ptr = array[0..array.len]; try expect(@TypeOf(array_ptr) == *[array.len]i32); // Using the address-of operator on a slice gives a single-item pointer, // while using the `ptr` field gives a many-item pointer. try expect(@TypeOf(slice.ptr) == [*]i32); try expect(@TypeOf(&slice[0]) == *i32); try expect(@ptrToInt(slice.ptr) == @ptrToInt(&slice[0])); // Slices have array bounds checking. If you try to access something out // of bounds, you'll get a safety check failure: slice[10] += 1; // Note that `slice.ptr` does not invoke safety checking, while `&slice[0]` // asserts that the slice has len >= 1. } {#code_end#}This is one reason we prefer slices to pointers.
{#code_begin|test|slices#} const std = @import("std"); const expect = std.testing.expect; const mem = std.mem; const fmt = std.fmt; test "using slices for strings" { // Zig has no concept of strings. String literals are const pointers // to null-terminated arrays of u8, and by convention parameters // that are "strings" are expected to be UTF-8 encoded slices of u8. // Here we coerce *const [5:0]u8 and *const [6:0]u8 to []const u8 const hello: []const u8 = "hello"; const world: []const u8 = "世界"; var all_together: [100]u8 = undefined; // You can use slice syntax on an array to convert an array into a slice. const all_together_slice = all_together[0..]; // String concatenation example. const hello_world = try fmt.bufPrint(all_together_slice, "{s} {s}", .{ hello, world }); // Generally, you can use UTF-8 and not worry about whether something is a // string. If you don't need to deal with individual characters, no need // to decode. try expect(mem.eql(u8, hello_world, "hello 世界")); } test "slice pointer" { var a: []u8 = undefined; try expect(@TypeOf(a) == []u8); var array: [10]u8 = undefined; const ptr = &array; try expect(@TypeOf(ptr) == *[10]u8); // A pointer to an array can be sliced just like an array: var start: usize = 0; var end: usize = 5; const slice = ptr[start..end]; slice[2] = 3; try expect(slice[2] == 3); // The slice is mutable because we sliced a mutable pointer. try expect(@TypeOf(slice) == []u8); // Again, slicing with constant indexes will produce another pointer to an array: const ptr2 = slice[2..3]; try expect(ptr2.len == 1); try expect(ptr2[0] == 3); try expect(@TypeOf(ptr2) == *[1]u8); } {#code_end#} {#see_also|Pointers|for|Arrays#} {#header_open|Sentinel-Terminated Slices#}The syntax {#syntax#}[:x]T{#endsyntax#} is a slice which has a runtime known length and also guarantees a sentinel value at the element indexed by the length. The type does not guarantee that there are no sentinel elements before that. Sentinel-terminated slices allow element access to the {#syntax#}len{#endsyntax#} index.
{#code_begin|test|null_terminated_slice#} const std = @import("std"); const expect = std.testing.expect; test "null terminated slice" { const slice: [:0]const u8 = "hello"; try expect(slice.len == 5); try expect(slice[5] == 0); } {#code_end#}Sentinel-terminated slices can also be created using a variation of the slice syntax {#syntax#}data[start..end :x]{#endsyntax#}, where {#syntax#}data{#endsyntax#} is a many-item pointer, array or slice and {#syntax#}x{#endsyntax#} is the sentinel value.
{#code_begin|test|null_terminated_slicing#} const std = @import("std"); const expect = std.testing.expect; test "null terminated slicing" { var array = [_]u8{ 3, 2, 1, 0, 3, 2, 1, 0 }; var runtime_length: usize = 3; const slice = array[0..runtime_length :0]; try expect(@TypeOf(slice) == [:0]u8); try expect(slice.len == 3); } {#code_end#}Sentinel-terminated slicing asserts that the element in the sentinel position of the backing data is actually the sentinel value. If this is not the case, safety-protected {#link|Undefined Behavior#} results.
{#code_begin|test_safety|sentinel mismatch#} const std = @import("std"); const expect = std.testing.expect; test "sentinel mismatch" { var array = [_]u8{ 3, 2, 1, 0 }; // Creating a sentinel-terminated slice from the array with a length of 2 // will result in the value `1` occupying the sentinel element position. // This does not match the indicated sentinel value of `0` and will lead // to a runtime panic. var runtime_length: usize = 2; const slice = array[0..runtime_length :0]; _ = slice; } {#code_end#} {#see_also|Sentinel-Terminated Pointers|Sentinel-Terminated Arrays#} {#header_close#} {#header_close#} {#header_open|struct#} {#code_begin|test|structs#} // Declare a struct. // Zig gives no guarantees about the order of fields and the size of // the struct but the fields are guaranteed to be ABI-aligned. const Point = struct { x: f32, y: f32, }; // Maybe we want to pass it to OpenGL so we want to be particular about // how the bytes are arranged. const Point2 = packed struct { x: f32, y: f32, }; // Declare an instance of a struct. const p = Point { .x = 0.12, .y = 0.34, }; // Maybe we're not ready to fill out some of the fields. var p2 = Point { .x = 0.12, .y = undefined, }; // Structs can have methods // Struct methods are not special, they are only namespaced // functions that you can call with dot syntax. const Vec3 = struct { x: f32, y: f32, z: f32, pub fn init(x: f32, y: f32, z: f32) Vec3 { return Vec3 { .x = x, .y = y, .z = z, }; } pub fn dot(self: Vec3, other: Vec3) f32 { return self.x * other.x + self.y * other.y + self.z * other.z; } }; const expect = @import("std").testing.expect; test "dot product" { const v1 = Vec3.init(1.0, 0.0, 0.0); const v2 = Vec3.init(0.0, 1.0, 0.0); try expect(v1.dot(v2) == 0.0); // Other than being available to call with dot syntax, struct methods are // not special. You can reference them as any other declaration inside // the struct: try expect(Vec3.dot(v1, v2) == 0.0); } // Structs can have declarations. // Structs can have 0 fields. const Empty = struct { pub const PI = 3.14; }; test "struct namespaced variable" { try expect(Empty.PI == 3.14); try expect(@sizeOf(Empty) == 0); // you can still instantiate an empty struct const does_nothing = Empty {}; _ = does_nothing; } // struct field order is determined by the compiler for optimal performance. // however, you can still calculate a struct base pointer given a field pointer: fn setYBasedOnX(x: *f32, y: f32) void { const point = @fieldParentPtr(Point, "x", x); point.y = y; } test "field parent pointer" { var point = Point { .x = 0.1234, .y = 0.5678, }; setYBasedOnX(&point.x, 0.9); try expect(point.y == 0.9); } // You can return a struct from a function. This is how we do generics // in Zig: fn LinkedList(comptime T: type) type { return struct { pub const Node = struct { prev: ?*Node, next: ?*Node, data: T, }; first: ?*Node, last: ?*Node, len: usize, }; } test "linked list" { // Functions called at compile-time are memoized. This means you can // do this: try expect(LinkedList(i32) == LinkedList(i32)); var list = LinkedList(i32) { .first = null, .last = null, .len = 0, }; try expect(list.len == 0); // Since types are first class values you can instantiate the type // by assigning it to a variable: const ListOfInts = LinkedList(i32); try expect(ListOfInts == LinkedList(i32)); var node = ListOfInts.Node { .prev = null, .next = null, .data = 1234, }; var list2 = LinkedList(i32) { .first = &node, .last = &node, .len = 1, }; // When using a pointer to a struct, fields can be accessed directly, // without explicitly dereferencing the pointer. // So you can do try expect(list2.first.?.data == 1234); // instead of try expect(list2.first.?.*.data == 1234); } {#code_end#} {#header_open|Default Field Values#}Each struct field may have an expression indicating the default field value. Such expressions are executed at {#link|comptime#}, and allow the field to be omitted in a struct literal expression:
{#code_begin|test|default_field_values#} const Foo = struct { a: i32 = 1234, b: i32, }; test "default struct initialization fields" { const x = Foo{ .b = 5, }; if (x.a + x.b != 1239) { @compileError("it's even comptime known!"); } } {#code_end#} {#header_close#} {#header_open|extern struct#}An {#syntax#}extern struct{#endsyntax#} has in-memory layout guaranteed to match the C ABI for the target.
This kind of struct should only be used for compatibility with the C ABI. Every other use case should be solved with {#link|packed struct#} or normal {#link|struct#}.
{#see_also|extern union|extern enum#} {#header_close#} {#header_open|packed struct#}Unlike normal structs, {#syntax#}packed{#endsyntax#} structs have guaranteed in-memory layout:
- Fields remain in the order declared, least to most significant.
- There is no padding between fields.
- Zig supports arbitrary width {#link|Integers#} and although normally, integers with fewer than 8 bits will still use 1 byte of memory, in packed structs, they use exactly their bit width.
- {#syntax#}bool{#endsyntax#} fields use exactly 1 bit.
- An {#link|enum#} field uses exactly the bit width of its integer tag type.
- A {#link|packed union#} field uses exactly the bit width of the union field with the largest bit width.
- Non-ABI-aligned fields are packed into the smallest possible ABI-aligned integers in accordance with the target endianness.
This means that a {#syntax#}packed struct{#endsyntax#} can participate in a {#link|@bitCast#} or a {#link|@ptrCast#} to reinterpret memory. This even works at {#link|comptime#}:
{#code_begin|test|packed_structs#} const std = @import("std"); const native_endian = @import("builtin").target.cpu.arch.endian(); const expect = std.testing.expect; const Full = packed struct { number: u16, }; const Divided = packed struct { half1: u8, quarter3: u4, quarter4: u4, }; test "@bitCast between packed structs" { try doTheTest(); comptime try doTheTest(); } fn doTheTest() !void { try expect(@sizeOf(Full) == 2); try expect(@sizeOf(Divided) == 2); var full = Full{ .number = 0x1234 }; var divided = @bitCast(Divided, full); try expect(divided.half1 == 0x34); try expect(divided.quarter3 == 0x2); try expect(divided.quarter4 == 0x1); var ordered = @bitCast([2]u8, full); switch (native_endian) { .Big => { try expect(ordered[0] == 0x12); try expect(ordered[1] == 0x34); }, .Little => { try expect(ordered[0] == 0x34); try expect(ordered[1] == 0x12); }, } } {#code_end#}Zig allows the address to be taken of a non-byte-aligned field:
{#code_begin|test|pointer_to_non-byte_aligned_field#} const std = @import("std"); const expect = std.testing.expect; const BitField = packed struct { a: u3, b: u3, c: u2, }; var foo = BitField{ .a = 1, .b = 2, .c = 3, }; test "pointer to non-byte-aligned field" { const ptr = &foo.b; try expect(ptr.* == 2); } {#code_end#}However, the pointer to a non-byte-aligned field has special properties and cannot be passed when a normal pointer is expected:
{#code_begin|test_err|expected type#} const std = @import("std"); const expect = std.testing.expect; const BitField = packed struct { a: u3, b: u3, c: u2, }; var bit_field = BitField{ .a = 1, .b = 2, .c = 3, }; test "pointer to non-bit-aligned field" { try expect(bar(&bit_field.b) == 2); } fn bar(x: *const u3) u3 { return x.*; } {#code_end#}In this case, the function {#syntax#}bar{#endsyntax#} cannot be called because the pointer to the non-ABI-aligned field mentions the bit offset, but the function expects an ABI-aligned pointer.
Pointers to non-ABI-aligned fields share the same address as the other fields within their host integer:
{#code_begin|test|packed_struct_field_addrs#} const std = @import("std"); const expect = std.testing.expect; const BitField = packed struct { a: u3, b: u3, c: u2, }; var bit_field = BitField{ .a = 1, .b = 2, .c = 3, }; test "pointers of sub-byte-aligned fields share addresses" { try expect(@ptrToInt(&bit_field.a) == @ptrToInt(&bit_field.b)); try expect(@ptrToInt(&bit_field.a) == @ptrToInt(&bit_field.c)); } {#code_end#}This can be observed with {#link|@bitOffsetOf#} and {#link|offsetOf#}:
{#code_begin|test|test_bitOffsetOf_offsetOf#} const std = @import("std"); const expect = std.testing.expect; const BitField = packed struct { a: u3, b: u3, c: u2, }; test "pointer to non-bit-aligned field" { comptime { try expect(@bitOffsetOf(BitField, "a") == 0); try expect(@bitOffsetOf(BitField, "b") == 3); try expect(@bitOffsetOf(BitField, "c") == 6); try expect(@offsetOf(BitField, "a") == 0); try expect(@offsetOf(BitField, "b") == 0); try expect(@offsetOf(BitField, "c") == 0); } } {#code_end#}Packed structs have the same alignment as their backing integer, however, overaligned pointers to packed structs can override this:
{#code_begin|test|overaligned_packed_struct#} const std = @import("std"); const expect = std.testing.expect; const S = packed struct { a: u32, b: u32, }; test "overaligned pointer to packed struct" { var foo: S align(4) = .{ .a = 1, .b = 2 }; const ptr: *align(4) S = &foo; const ptr_to_b: *u32 = &ptr.b; try expect(ptr_to_b.* == 2); } {#code_end#}It's also possible to set alignment of struct fields:
{#code_begin|test|test_aligned_struct_fields#} const std = @import("std"); const expectEqual = std.testing.expectEqual; test "aligned struct fields" { const S = struct { a: u32 align(2), b: u32 align(64), }; var foo = S{ .a = 1, .b = 2 }; try expectEqual(64, @alignOf(S)); try expectEqual(*align(2) u32, @TypeOf(&foo.a)); try expectEqual(*align(64) u32, @TypeOf(&foo.b)); } {#code_end#}Using packed structs with {#link|volatile#} is problematic, and may be a compile error in the future. For details on this subscribe to this issue. TODO update these docs with a recommendation on how to use packed structs with MMIO (the use case for volatile packed structs) once this issue is resolved. Don't worry, there will be a good solution for this use case in zig.
{#header_close#} {#header_open|Struct Naming#}Since all structs are anonymous, Zig infers the type name based on a few rules.
- If the struct is in the initialization expression of a variable, it gets named after that variable.
- If the struct is in the {#syntax#}return{#endsyntax#} expression, it gets named after the function it is returning from, with the parameter values serialized.
- Otherwise, the struct gets a name such as
(anonymous struct at file.zig:7:38)
. - If the struct is declared inside another struct, it gets named after both the parent struct and the name inferred by the previous rules, separated by a dot.
Zig allows omitting the struct type of a literal. When the result is {#link|coerced|Type Coercion#}, the struct literal will directly instantiate the result location, with no copy:
{#code_begin|test|struct_result#} const std = @import("std"); const expect = std.testing.expect; const Point = struct {x: i32, y: i32}; test "anonymous struct literal" { var pt: Point = .{ .x = 13, .y = 67, }; try expect(pt.x == 13); try expect(pt.y == 67); } {#code_end#}The struct type can be inferred. Here the result location does not include a type, and so Zig infers the type:
{#code_begin|test|struct_anon#} const std = @import("std"); const expect = std.testing.expect; test "fully anonymous struct" { try dump(.{ .int = @as(u32, 1234), .float = @as(f64, 12.34), .b = true, .s = "hi", }); } fn dump(args: anytype) !void { try expect(args.int == 1234); try expect(args.float == 12.34); try expect(args.b); try expect(args.s[0] == 'h'); try expect(args.s[1] == 'i'); } {#code_end#}Anonymous structs can be created without specifying field names, and are referred to as "tuples".
The fields are implicitly named using numbers starting from 0. Because their names are integers, the {#syntax#}@"0"{#endsyntax#} syntax must be used to access them. Names inside {#syntax#}@""{#endsyntax#} are always recognised as {#link|identifiers|Identifiers#}.
Like arrays, tuples have a .len field, can be indexed and work with the ++ and ** operators. They can also be iterated over with {#link|inline for#}.
{#code_begin|test|tuple#} const std = @import("std"); const expect = std.testing.expect; test "tuple" { const values = .{ @as(u32, 1234), @as(f64, 12.34), true, "hi", } ++ .{false} ** 2; try expect(values[0] == 1234); try expect(values[4] == false); inline for (values) |v, i| { if (i != 2) continue; try expect(v); } try expect(values.len == 6); try expect(values.@"3"[0] == 'h'); } {#code_end#} {#header_close#} {#see_also|comptime|@fieldParentPtr#} {#header_close#} {#header_open|enum#} {#code_begin|test|enums#} const expect = @import("std").testing.expect; const mem = @import("std").mem; // Declare an enum. const Type = enum { ok, not_ok, }; // Declare a specific instance of the enum variant. const c = Type.ok; // If you want access to the ordinal value of an enum, you // can specify the tag type. const Value = enum(u2) { zero, one, two, }; // Now you can cast between u2 and Value. // The ordinal value starts from 0, counting up for each member. test "enum ordinal value" { try expect(@enumToInt(Value.zero) == 0); try expect(@enumToInt(Value.one) == 1); try expect(@enumToInt(Value.two) == 2); } // You can override the ordinal value for an enum. const Value2 = enum(u32) { hundred = 100, thousand = 1000, million = 1000000, }; test "set enum ordinal value" { try expect(@enumToInt(Value2.hundred) == 100); try expect(@enumToInt(Value2.thousand) == 1000); try expect(@enumToInt(Value2.million) == 1000000); } // Enums can have methods, the same as structs and unions. // Enum methods are not special, they are only namespaced // functions that you can call with dot syntax. const Suit = enum { clubs, spades, diamonds, hearts, pub fn isClubs(self: Suit) bool { return self == Suit.clubs; } }; test "enum method" { const p = Suit.spades; try expect(!p.isClubs()); } // An enum variant of different types can be switched upon. const Foo = enum { string, number, none, }; test "enum variant switch" { const p = Foo.number; const what_is_it = switch (p) { Foo.string => "this is a string", Foo.number => "this is a number", Foo.none => "this is a none", }; try expect(mem.eql(u8, what_is_it, "this is a number")); } // @typeInfo can be used to access the integer tag type of an enum. const Small = enum { one, two, three, four, }; test "std.meta.Tag" { try expect(@typeInfo(Small).Enum.tag_type == u2); } // @typeInfo tells us the field count and the fields names: test "@typeInfo" { try expect(@typeInfo(Small).Enum.fields.len == 4); try expect(mem.eql(u8, @typeInfo(Small).Enum.fields[1].name, "two")); } // @tagName gives a [:0]const u8 representation of an enum value: test "@tagName" { try expect(mem.eql(u8, @tagName(Small.three), "three")); } {#code_end#} {#see_also|@typeInfo|@tagName|@sizeOf#} {#header_open|extern enum#}By default, enums are not guaranteed to be compatible with the C ABI:
{#code_begin|obj_err|parameter of type 'test.Foo' not allowed in function with calling convention 'C'#} const Foo = enum { a, b, c }; export fn entry(foo: Foo) void { _ = foo; } {#code_end#}For a C-ABI-compatible enum, provide an explicit tag type to the enum:
{#code_begin|obj#} const Foo = enum(c_int) { a, b, c }; export fn entry(foo: Foo) void { _ = foo; } {#code_end#} {#header_close#} {#header_open|Enum Literals#}Enum literals allow specifying the name of an enum field without specifying the enum type:
{#code_begin|test|test_enum_literals#} const std = @import("std"); const expect = std.testing.expect; const Color = enum { auto, off, on, }; test "enum literals" { const color1: Color = .auto; const color2 = Color.auto; try expect(color1 == color2); } test "switch using enum literals" { const color = Color.on; const result = switch (color) { .auto => false, .on => true, .off => false, }; try expect(result); } {#code_end#} {#header_close#} {#header_open|Non-exhaustive enum#}A Non-exhaustive enum can be created by adding a trailing '_' field. It must specify a tag type and cannot consume every enumeration value.
{#link|@intToEnum#} on a non-exhaustive enum involves the safety semantics of {#link|@intCast#} to the integer tag type, but beyond that always results in a well-defined enum value.
A switch on a non-exhaustive enum can include a '_' prong as an alternative to an {#syntax#}else{#endsyntax#} prong with the difference being that it makes it a compile error if all the known tag names are not handled by the switch.
{#code_begin|test|test_switch_non-exhaustive#} const std = @import("std"); const expect = std.testing.expect; const Number = enum(u8) { one, two, three, _, }; test "switch on non-exhaustive enum" { const number = Number.one; const result = switch (number) { .one => true, .two, .three => false, _ => false, }; try expect(result); const is_one = switch (number) { .one => true, else => false, }; try expect(is_one); } {#code_end#} {#header_close#} {#header_close#} {#header_open|union#}A bare {#syntax#}union{#endsyntax#} defines a set of possible types that a value can be as a list of fields. Only one field can be active at a time. The in-memory representation of bare unions is not guaranteed. Bare unions cannot be used to reinterpret memory. For that, use {#link|@ptrCast#}, or use an {#link|extern union#} or a {#link|packed union#} which have guaranteed in-memory layout. {#link|Accessing the non-active field|Wrong Union Field Access#} is safety-checked {#link|Undefined Behavior#}:
{#code_begin|test_err|inactive union field#} const Payload = union { int: i64, float: f64, boolean: bool, }; test "simple union" { var payload = Payload{ .int = 1234 }; payload.float = 12.34; } {#code_end#}You can activate another field by assigning the entire union:
{#code_begin|test|test_simple_union#} const std = @import("std"); const expect = std.testing.expect; const Payload = union { int: i64, float: f64, boolean: bool, }; test "simple union" { var payload = Payload{ .int = 1234 }; try expect(payload.int == 1234); payload = Payload{ .float = 12.34 }; try expect(payload.float == 12.34); } {#code_end#}In order to use {#link|switch#} with a union, it must be a {#link|Tagged union#}.
To initialize a union when the tag is a {#link|comptime#}-known name, see {#link|@unionInit#}.
{#header_open|Tagged union#}Unions can be declared with an enum tag type. This turns the union into a tagged union, which makes it eligible to use with {#link|switch#} expressions. Tagged unions coerce to their tag type: {#link|Type Coercion: unions and enums#}.
{#code_begin|test|test_switch_tagged_union#} const std = @import("std"); const expect = std.testing.expect; const ComplexTypeTag = enum { ok, not_ok, }; const ComplexType = union(ComplexTypeTag) { ok: u8, not_ok: void, }; test "switch on tagged union" { const c = ComplexType{ .ok = 42 }; try expect(@as(ComplexTypeTag, c) == ComplexTypeTag.ok); switch (c) { ComplexTypeTag.ok => |value| try expect(value == 42), ComplexTypeTag.not_ok => unreachable, } } test "get tag type" { try expect(std.meta.Tag(ComplexType) == ComplexTypeTag); } test "coerce to enum" { const c1 = ComplexType{ .ok = 42 }; const c2 = ComplexType.not_ok; try expect(c1 == .ok); try expect(c2 == .not_ok); } {#code_end#}In order to modify the payload of a tagged union in a switch expression, place a {#syntax#}*{#endsyntax#} before the variable name to make it a pointer:
{#code_begin|test|test_switch_modify_tagged_union#} const std = @import("std"); const expect = std.testing.expect; const ComplexTypeTag = enum { ok, not_ok, }; const ComplexType = union(ComplexTypeTag) { ok: u8, not_ok: void, }; test "modify tagged union in switch" { var c = ComplexType{ .ok = 42 }; try expect(@as(ComplexTypeTag, c) == ComplexTypeTag.ok); switch (c) { ComplexTypeTag.ok => |*value| value.* += 1, ComplexTypeTag.not_ok => unreachable, } try expect(c.ok == 43); } {#code_end#}Unions can be made to infer the enum tag type. Further, unions can have methods just like structs and enums.
{#code_begin|test|test_union_method#} const std = @import("std"); const expect = std.testing.expect; const Variant = union(enum) { int: i32, boolean: bool, // void can be omitted when inferring enum tag type. none, fn truthy(self: Variant) bool { return switch (self) { Variant.int => |x_int| x_int != 0, Variant.boolean => |x_bool| x_bool, Variant.none => false, }; } }; test "union method" { var v1 = Variant{ .int = 1 }; var v2 = Variant{ .boolean = false }; try expect(v1.truthy()); try expect(!v2.truthy()); } {#code_end#}{#link|@tagName#} can be used to return a {#link|comptime#} {#syntax#}[:0]const u8{#endsyntax#} value representing the field name:
{#code_begin|test|test_tagName#} const std = @import("std"); const expect = std.testing.expect; const Small2 = union(enum) { a: i32, b: bool, c: u8, }; test "@tagName" { try expect(std.mem.eql(u8, @tagName(Small2.a), "a")); } {#code_end#} {#header_close#} {#header_open|extern union#}An {#syntax#}extern union{#endsyntax#} has memory layout guaranteed to be compatible with the target C ABI.
{#see_also|extern struct#} {#header_close#} {#header_open|packed union#}A {#syntax#}packed union{#endsyntax#} has well-defined in-memory layout and is eligible to be in a {#link|packed struct#}.
{#header_close#} {#header_open|Anonymous Union Literals#}{#link|Anonymous Struct Literals#} syntax can be used to initialize unions without specifying the type:
{#code_begin|test|anon_union#} const std = @import("std"); const expect = std.testing.expect; const Number = union { int: i32, float: f64, }; test "anonymous union literal syntax" { var i: Number = .{.int = 42}; var f = makeNumber(); try expect(i.int == 42); try expect(f.float == 12.34); } fn makeNumber() Number { return .{.float = 12.34}; } {#code_end#} {#header_close#} {#header_close#} {#header_open|opaque#}{#syntax#}opaque {}{#endsyntax#} declares a new type with an unknown (but non-zero) size and alignment. It can contain declarations the same as {#link|structs|struct#}, {#link|unions|union#}, and {#link|enums|enum#}.
This is typically used for type safety when interacting with C code that does not expose struct details. Example:
{#code_begin|test_err|expected type '*test.Derp', found '*test.Wat'#} const Derp = opaque {}; const Wat = opaque {}; extern fn bar(d: *Derp) void; fn foo(w: *Wat) callconv(.C) void { bar(w); } test "call foo" { foo(undefined); } {#code_end#} {#header_close#} {#header_open|Blocks#}Blocks are used to limit the scope of variable declarations:
{#code_begin|test_err|use of undeclared identifier 'x'#} test "access variable after block scope" { { var x: i32 = 1; _ = x; } x += 1; } {#code_end#}Blocks are expressions. When labeled, {#syntax#}break{#endsyntax#} can be used to return a value from the block:
{#code_begin|test|test_labeled_break#} const std = @import("std"); const expect = std.testing.expect; test "labeled break from labeled block expression" { var y: i32 = 123; const x = blk: { y += 1; break :blk y; }; try expect(x == 124); try expect(y == 124); } {#code_end#}Here, {#syntax#}blk{#endsyntax#} can be any name.
{#see_also|Labeled while|Labeled for#} {#header_open|Shadowing#}{#link|Identifiers#} are never allowed to "hide" other identifiers by using the same name:
{#code_begin|test_err|local variable shadows declaration#} const pi = 3.14; test "inside test block" { // Let's even go inside another block { var pi: i32 = 1234; } } {#code_end#}Because of this, when you read Zig code you can always rely on an identifier to consistently mean the same thing within the scope it is defined. Note that you can, however, use the same name if the scopes are separate:
{#code_begin|test|test_scopes#} test "separate scopes" { { const pi = 3.14; _ = pi; } { var pi: bool = true; _ = pi; } } {#code_end#} {#header_close#} {#header_open|Empty Blocks#}An empty block is equivalent to {#syntax#}void{}{#endsyntax#}:
{#code_begin|test|empty_block#} const std = @import("std"); const expect = std.testing.expect; test { const a = {}; const b = void{}; try expect(@TypeOf(a) == void); try expect(@TypeOf(b) == void); try expect(a == b); } {#code_end#} {#header_close#} {#header_close#} {#header_open|switch#} {#code_begin|test|switch#} const std = @import("std"); const builtin = @import("builtin"); const expect = std.testing.expect; test "switch simple" { const a: u64 = 10; const zz: u64 = 103; // All branches of a switch expression must be able to be coerced to a // common type. // // Branches cannot fallthrough. If fallthrough behavior is desired, combine // the cases and use an if. const b = switch (a) { // Multiple cases can be combined via a ',' 1, 2, 3 => 0, // Ranges can be specified using the ... syntax. These are inclusive // of both ends. 5...100 => 1, // Branches can be arbitrarily complex. 101 => blk: { const c: u64 = 5; break :blk c * 2 + 1; }, // Switching on arbitrary expressions is allowed as long as the // expression is known at compile-time. zz => zz, blk: { const d: u32 = 5; const e: u32 = 100; break :blk d + e; } => 107, // The else branch catches everything not already captured. // Else branches are mandatory unless the entire range of values // is handled. else => 9, }; try expect(b == 1); } // Switch expressions can be used outside a function: const os_msg = switch (builtin.target.os.tag) { .linux => "we found a linux user", else => "not a linux user", }; // Inside a function, switch statements implicitly are compile-time // evaluated if the target expression is compile-time known. test "switch inside function" { switch (builtin.target.os.tag) { .fuchsia => { // On an OS other than fuchsia, block is not even analyzed, // so this compile error is not triggered. // On fuchsia this compile error would be triggered. @compileError("fuchsia not supported"); }, else => {}, } } {#code_end#}{#syntax#}switch{#endsyntax#} can be used to capture the field values of a {#link|Tagged union#}. Modifications to the field values can be done by placing a {#syntax#}*{#endsyntax#} before the capture variable name, turning it into a pointer.
{#code_begin|test|test_switch_tagged_union#} const expect = @import("std").testing.expect; test "switch on tagged union" { const Point = struct { x: u8, y: u8, }; const Item = union(enum) { a: u32, c: Point, d, e: u32, }; var a = Item{ .c = Point{ .x = 1, .y = 2 } }; // Switching on more complex enums is allowed. const b = switch (a) { // A capture group is allowed on a match, and will return the enum // value matched. If the payload types of both cases are the same // they can be put into the same switch prong. Item.a, Item.e => |item| item, // A reference to the matched value can be obtained using `*` syntax. Item.c => |*item| blk: { item.*.x += 1; break :blk 6; }, // No else is required if the types cases was exhaustively handled Item.d => 8, }; try expect(b == 6); try expect(a.c.x == 2); } {#code_end#} {#see_also|comptime|enum|@compileError|Compile Variables#} {#header_open|Exhaustive Switching#}When a {#syntax#}switch{#endsyntax#} expression does not have an {#syntax#}else{#endsyntax#} clause, it must exhaustively list all the possible values. Failure to do so is a compile error:
{#code_begin|test_err|unhandled enumeration value#} const Color = enum { auto, off, on, }; test "exhaustive switching" { const color = Color.off; switch (color) { Color.auto => {}, Color.on => {}, } } {#code_end#} {#header_close#} {#header_open|Switching with Enum Literals#}{#link|Enum Literals#} can be useful to use with {#syntax#}switch{#endsyntax#} to avoid repetitively specifying {#link|enum#} or {#link|union#} types:
{#code_begin|test|test_exhaustive_switch#} const std = @import("std"); const expect = std.testing.expect; const Color = enum { auto, off, on, }; test "enum literals with switch" { const color = Color.off; const result = switch (color) { .auto => false, .on => false, .off => true, }; try expect(result); } {#code_end#} {#header_close#} {#header_open|Inline switch#}Switch prongs can be marked as {#syntax#}inline{#endsyntax#} to generate the prong's body for each possible value it could have:
{#code_begin|test|test_inline_switch#} const std = @import("std"); const expect = std.testing.expect; const expectError = std.testing.expectError; fn isFieldOptional(comptime T: type, field_index: usize) !bool { const fields = @typeInfo(T).Struct.fields; return switch (field_index) { // This prong is analyzed `fields.len - 1` times with `idx` being an // unique comptime known value each time. inline 0...fields.len - 1 => |idx| @typeInfo(fields[idx].field_type) == .Optional, else => return error.IndexOutOfBounds, }; } const Struct1 = struct { a: u32, b: ?u32 }; test "using @typeInfo with runtime values" { var index: usize = 0; try expect(!try isFieldOptional(Struct1, index)); index += 1; try expect(try isFieldOptional(Struct1, index)); index += 1; try expectError(error.IndexOutOfBounds, isFieldOptional(Struct1, index)); } // Calls to `isFieldOptional` on `Struct1` get unrolled to an equivalent // of this function: fn isFieldOptionalUnrolled(field_index: usize) !bool { return switch (field_index) { 0 => false, 1 => true, else => return error.IndexOutOfBounds, }; } {#code_end#}{#syntax#}inline else{#endsyntax#} prongs can be used as a type safe alternative to {#syntax#}inline for{#endsyntax#} loops:
{#code_begin|test|test_inline_else#} const std = @import("std"); const expect = std.testing.expect; const SliceTypeA = extern struct { len: usize, ptr: [*]u32, }; const SliceTypeB = extern struct { ptr: [*]SliceTypeA, len: usize, }; const AnySlice = union(enum) { a: SliceTypeA, b: SliceTypeB, c: []const u8, d: []AnySlice, }; fn withFor(any: AnySlice) usize { const Tag = @typeInfo(AnySlice).Union.tag_type.?; inline for (@typeInfo(Tag).Enum.fields) |field| { // With `inline for` the function gets generated as // a series of `if` statements relying on the optimizer // to convert it to a switch. if (field.value == @enumToInt(any)) { return @field(any, field.name).len; } } // When using `inline for` the compiler doesn't know that every // possible case has been handled requiring an explicit `unreachable`. unreachable; } fn withSwitch(any: AnySlice) usize { return switch (any) { // With `inline else` the function is explicitly generated // as the desired switch and the compiler can check that // every possible case is handled. inline else => |slice| slice.len, }; } test "inline for and inline else similarity" { var any = AnySlice{ .c = "hello" }; try expect(withFor(any) == 5); try expect(withSwitch(any) == 5); } {#code_end#}When using an inline prong switching on an union an additional capture can be used to obtain the union's enum tag value.
{#code_begin|test|test_inline_switch_union_tag#} const std = @import("std"); const expect = std.testing.expect; const U = union(enum) { a: u32, b: f32, }; fn getNum(u: U) u32 { switch (u) { // Here `num` is a runtime known value that is either // `u.a` or `u.b` and `tag` is `u`'s comptime known tag value. inline else => |num, tag| { if (tag == .b) { return @floatToInt(u32, num); } return num; } } } test "test" { var u = U{ .b = 42 }; try expect(getNum(u) == 42); } {#code_end#} {#see_also|inline while|inline for#} {#header_close#} {#header_close#} {#header_open|while#}A while loop is used to repeatedly execute an expression until some condition is no longer true.
{#code_begin|test|while#} const expect = @import("std").testing.expect; test "while basic" { var i: usize = 0; while (i < 10) { i += 1; } try expect(i == 10); } {#code_end#}Use {#syntax#}break{#endsyntax#} to exit a while loop early.
{#code_begin|test|while#} const expect = @import("std").testing.expect; test "while break" { var i: usize = 0; while (true) { if (i == 10) break; i += 1; } try expect(i == 10); } {#code_end#}Use {#syntax#}continue{#endsyntax#} to jump back to the beginning of the loop.
{#code_begin|test|while#} const expect = @import("std").testing.expect; test "while continue" { var i: usize = 0; while (true) { i += 1; if (i < 10) continue; break; } try expect(i == 10); } {#code_end#}While loops support a continue expression which is executed when the loop is continued. The {#syntax#}continue{#endsyntax#} keyword respects this expression.
{#code_begin|test|while#} const expect = @import("std").testing.expect; test "while loop continue expression" { var i: usize = 0; while (i < 10) : (i += 1) {} try expect(i == 10); } test "while loop continue expression, more complicated" { var i: usize = 1; var j: usize = 1; while (i * j < 2000) : ({ i *= 2; j *= 3; }) { const my_ij = i * j; try expect(my_ij < 2000); } } {#code_end#}While loops are expressions. The result of the expression is the result of the {#syntax#}else{#endsyntax#} clause of a while loop, which is executed when the condition of the while loop is tested as false.
{#syntax#}break{#endsyntax#}, like {#syntax#}return{#endsyntax#}, accepts a value parameter. This is the result of the {#syntax#}while{#endsyntax#} expression. When you {#syntax#}break{#endsyntax#} from a while loop, the {#syntax#}else{#endsyntax#} branch is not evaluated.
{#code_begin|test|while#} const expect = @import("std").testing.expect; test "while else" { try expect(rangeHasNumber(0, 10, 5)); try expect(!rangeHasNumber(0, 10, 15)); } fn rangeHasNumber(begin: usize, end: usize, number: usize) bool { var i = begin; return while (i < end) : (i += 1) { if (i == number) { break true; } } else false; } {#code_end#} {#header_open|Labeled while#}When a {#syntax#}while{#endsyntax#} loop is labeled, it can be referenced from a {#syntax#}break{#endsyntax#} or {#syntax#}continue{#endsyntax#} from within a nested loop:
{#code_begin|test|test_nested_break#} test "nested break" { outer: while (true) { while (true) { break :outer; } } } test "nested continue" { var i: usize = 0; outer: while (i < 10) : (i += 1) { while (true) { continue :outer; } } } {#code_end#} {#header_close#} {#header_open|while with Optionals#}Just like {#link|if#} expressions, while loops can take an optional as the condition and capture the payload. When {#link|null#} is encountered the loop exits.
When the {#syntax#}|x|{#endsyntax#} syntax is present on a {#syntax#}while{#endsyntax#} expression, the while condition must have an {#link|Optional Type#}.
The {#syntax#}else{#endsyntax#} branch is allowed on optional iteration. In this case, it will be executed on the first null value encountered.
{#code_begin|test|while#} const expect = @import("std").testing.expect; test "while null capture" { var sum1: u32 = 0; numbers_left = 3; while (eventuallyNullSequence()) |value| { sum1 += value; } try expect(sum1 == 3); var sum2: u32 = 0; numbers_left = 3; while (eventuallyNullSequence()) |value| { sum2 += value; } else { try expect(sum2 == 3); } } var numbers_left: u32 = undefined; fn eventuallyNullSequence() ?u32 { return if (numbers_left == 0) null else blk: { numbers_left -= 1; break :blk numbers_left; }; } {#code_end#} {#header_close#} {#header_open|while with Error Unions#}Just like {#link|if#} expressions, while loops can take an error union as the condition and capture the payload or the error code. When the condition results in an error code the else branch is evaluated and the loop is finished.
When the {#syntax#}else |x|{#endsyntax#} syntax is present on a {#syntax#}while{#endsyntax#} expression, the while condition must have an {#link|Error Union Type#}.
{#code_begin|test|while#} const expect = @import("std").testing.expect; test "while error union capture" { var sum1: u32 = 0; numbers_left = 3; while (eventuallyErrorSequence()) |value| { sum1 += value; } else |err| { try expect(err == error.ReachedZero); } } var numbers_left: u32 = undefined; fn eventuallyErrorSequence() anyerror!u32 { return if (numbers_left == 0) error.ReachedZero else blk: { numbers_left -= 1; break :blk numbers_left; }; } {#code_end#} {#header_close#} {#header_open|inline while#}While loops can be inlined. This causes the loop to be unrolled, which allows the code to do some things which only work at compile time, such as use types as first class values.
{#code_begin|test|test_inline_while#} const expect = @import("std").testing.expect; test "inline while loop" { comptime var i = 0; var sum: usize = 0; inline while (i < 3) : (i += 1) { const T = switch (i) { 0 => f32, 1 => i8, 2 => bool, else => unreachable, }; sum += typeNameLength(T); } try expect(sum == 9); } fn typeNameLength(comptime T: type) usize { return @typeName(T).len; } {#code_end#}It is recommended to use {#syntax#}inline{#endsyntax#} loops only for one of these reasons:
- You need the loop to execute at {#link|comptime#} for the semantics to work.
- You have a benchmark to prove that forcibly unrolling the loop in this way is measurably faster.
When a {#syntax#}for{#endsyntax#} loop is labeled, it can be referenced from a {#syntax#}break{#endsyntax#} or {#syntax#}continue{#endsyntax#} from within a nested loop:
{#code_begin|test|test_nested_break#} const std = @import("std"); const expect = std.testing.expect; test "nested break" { var count: usize = 0; outer: for ([_]i32{ 1, 2, 3, 4, 5 }) |_| { for ([_]i32{ 1, 2, 3, 4, 5 }) |_| { count += 1; break :outer; } } try expect(count == 1); } test "nested continue" { var count: usize = 0; outer: for ([_]i32{ 1, 2, 3, 4, 5, 6, 7, 8 }) |_| { for ([_]i32{ 1, 2, 3, 4, 5 }) |_| { count += 1; continue :outer; } } try expect(count == 8); } {#code_end#} {#header_close#} {#header_open|inline for#}For loops can be inlined. This causes the loop to be unrolled, which allows the code to do some things which only work at compile time, such as use types as first class values. The capture value and iterator value of inlined for loops are compile-time known.
{#code_begin|test|test_inline_loop#} const expect = @import("std").testing.expect; test "inline for loop" { const nums = [_]i32{2, 4, 6}; var sum: usize = 0; inline for (nums) |i| { const T = switch (i) { 2 => f32, 4 => i8, 6 => bool, else => unreachable, }; sum += typeNameLength(T); } try expect(sum == 9); } fn typeNameLength(comptime T: type) usize { return @typeName(T).len; } {#code_end#}It is recommended to use {#syntax#}inline{#endsyntax#} loops only for one of these reasons:
- You need the loop to execute at {#link|comptime#} for the semantics to work.
- You have a benchmark to prove that forcibly unrolling the loop in this way is measurably faster.
In {#link|Debug#} and {#link|ReleaseSafe#} mode
{#syntax#}unreachable{#endsyntax#} emits a call to {#syntax#}panic{#endsyntax#} with the message reached unreachable code
.
In {#link|ReleaseFast#} and {#link|ReleaseSmall#} mode, the optimizer uses the assumption that {#syntax#}unreachable{#endsyntax#} code will never be hit to perform optimizations.
{#header_open|Basics#} {#code_begin|test|test_unreachable#} // unreachable is used to assert that control flow will never reach a // particular location: test "basic math" { const x = 1; const y = 2; if (x + y != 3) { unreachable; } } {#code_end#}In fact, this is how {#syntax#}std.debug.assert{#endsyntax#} is implemented:
{#code_begin|test_err#} // This is how std.debug.assert is implemented fn assert(ok: bool) void { if (!ok) unreachable; // assertion failure } // This test will fail because we hit unreachable. test "this will fail" { assert(false); } {#code_end#} {#header_close#} {#header_open|At Compile-Time#} {#code_begin|test_err|unreachable code#} const assert = @import("std").debug.assert; test "type of unreachable" { comptime { // The type of unreachable is noreturn. // However this assertion will still fail to compile because // unreachable expressions are compile errors. assert(@TypeOf(unreachable) == noreturn); } } {#code_end#} {#see_also|Zig Test|Build Mode|comptime#} {#header_close#} {#header_close#} {#header_open|noreturn#}{#syntax#}noreturn{#endsyntax#} is the type of:
- {#syntax#}break{#endsyntax#}
- {#syntax#}continue{#endsyntax#}
- {#syntax#}return{#endsyntax#}
- {#syntax#}unreachable{#endsyntax#}
- {#syntax#}while (true) {}{#endsyntax#}
When resolving types together, such as {#syntax#}if{#endsyntax#} clauses or {#syntax#}switch{#endsyntax#} prongs, the {#syntax#}noreturn{#endsyntax#} type is compatible with every other type. Consider:
{#code_begin|test|test_noreturn#} fn foo(condition: bool, b: u32) void { const a = if (condition) b else return; _ = a; @panic("do something with a"); } test "noreturn" { foo(false, 1); } {#code_end#}Another use case for {#syntax#}noreturn{#endsyntax#} is the {#syntax#}exit{#endsyntax#} function:
{#code_begin|test|noreturn_from_exit#} {#target_windows#} const std = @import("std"); const builtin = @import("builtin"); const native_arch = builtin.cpu.arch; const expect = std.testing.expect; const WINAPI: std.builtin.CallingConvention = if (native_arch == .x86) .Stdcall else .C; extern "kernel32" fn ExitProcess(exit_code: c_uint) callconv(WINAPI) noreturn; test "foo" { const value = bar() catch ExitProcess(1); try expect(value == 1234); } fn bar() anyerror!u32 { return 1234; } {#code_end#} {#header_close#} {#header_open|Functions#} {#code_begin|test|functions#} const std = @import("std"); const builtin = @import("builtin"); const native_arch = builtin.cpu.arch; const expect = std.testing.expect; // Functions are declared like this fn add(a: i8, b: i8) i8 { if (a == 0) { return b; } return a + b; } // The export specifier makes a function externally visible in the generated // object file, and makes it use the C ABI. export fn sub(a: i8, b: i8) i8 { return a - b; } // The extern specifier is used to declare a function that will be resolved // at link time, when linking statically, or at runtime, when linking // dynamically. // The callconv specifier changes the calling convention of the function. const WINAPI: std.builtin.CallingConvention = if (native_arch == .x86) .Stdcall else .C; extern "kernel32" fn ExitProcess(exit_code: u32) callconv(WINAPI) noreturn; extern "c" fn atan2(a: f64, b: f64) f64; // The @setCold builtin tells the optimizer that a function is rarely called. fn abort() noreturn { @setCold(true); while (true) {} } // The naked calling convention makes a function not have any function prologue or epilogue. // This can be useful when integrating with assembly. fn _start() callconv(.Naked) noreturn { abort(); } // The inline calling convention forces a function to be inlined at all call sites. // If the function cannot be inlined, it is a compile-time error. fn shiftLeftOne(a: u32) callconv(.Inline) u32 { return a << 1; } // The pub specifier allows the function to be visible when importing. // Another file can use @import and call sub2 pub fn sub2(a: i8, b: i8) i8 { return a - b; } // Function pointers are prefixed with `*const `. const call2_op = *const fn (a: i8, b: i8) i8; fn do_op(fn_call: call2_op, op1: i8, op2: i8) i8 { return fn_call(op1, op2); } test "function" { try expect(do_op(add, 5, 6) == 11); try expect(do_op(sub2, 5, 6) == -1); } {#code_end#}There is a difference between a function body and a function pointer. Function bodies are {#link|comptime#}-only types while function {#link|Pointers#} may be runtime-known.
{#header_open|Pass-by-value Parameters#}Primitive types such as {#link|Integers#} and {#link|Floats#} passed as parameters are copied, and then the copy is available in the function body. This is called "passing by value". Copying a primitive type is essentially free and typically involves nothing more than setting a register.
Structs, unions, and arrays can sometimes be more efficiently passed as a reference, since a copy could be arbitrarily expensive depending on the size. When these types are passed as parameters, Zig may choose to copy and pass by value, or pass by reference, whichever way Zig decides will be faster. This is made possible, in part, by the fact that parameters are immutable.
{#code_begin|test|pass_by_reference_or_value#} const Point = struct { x: i32, y: i32, }; fn foo(point: Point) i32 { // Here, `point` could be a reference, or a copy. The function body // can ignore the difference and treat it as a value. Be very careful // taking the address of the parameter - it should be treated as if // the address will become invalid when the function returns. return point.x + point.y; } const expect = @import("std").testing.expect; test "pass struct to function" { try expect(foo(Point{ .x = 1, .y = 2 }) == 3); } {#code_end#}For extern functions, Zig follows the C ABI for passing structs and unions by value.
{#header_close#} {#header_open|Function Parameter Type Inference#}Function parameters can be declared with {#syntax#}anytype{#endsyntax#} in place of the type. In this case the parameter types will be inferred when the function is called. Use {#link|@TypeOf#} and {#link|@typeInfo#} to get information about the inferred type.
{#code_begin|test|test_fn_type_inference#} const expect = @import("std").testing.expect; fn addFortyTwo(x: anytype) @TypeOf(x) { return x + 42; } test "fn type inference" { try expect(addFortyTwo(1) == 43); try expect(@TypeOf(addFortyTwo(1)) == comptime_int); var y: i64 = 2; try expect(addFortyTwo(y) == 44); try expect(@TypeOf(addFortyTwo(y)) == i64); } {#code_end#} {#header_close#} {#header_open|Function Reflection#} {#code_begin|test|test_fn_reflection#} const expect = @import("std").testing.expect; test "fn reflection" { try expect(@typeInfo(@TypeOf(expect)).Fn.args[0].arg_type.? == bool); try expect(@typeInfo(@TypeOf(expect)).Fn.is_var_args == false); } {#code_end#} {#header_close#} {#header_close#} {#header_open|Errors#} {#header_open|Error Set Type#}An error set is like an {#link|enum#}. However, each error name across the entire compilation gets assigned an unsigned integer greater than 0. You are allowed to declare the same error name more than once, and if you do, it gets assigned the same integer value.
The number of unique error values across the entire compilation should determine the size of the error set type. However right now it is hard coded to be a {#syntax#}u16{#endsyntax#}. See #768.
You can {#link|coerce|Type Coercion#} an error from a subset to a superset:
{#code_begin|test|coercing_subset_to_superset#} const std = @import("std"); const FileOpenError = error { AccessDenied, OutOfMemory, FileNotFound, }; const AllocationError = error { OutOfMemory, }; test "coerce subset to superset" { const err = foo(AllocationError.OutOfMemory); try std.testing.expect(err == FileOpenError.OutOfMemory); } fn foo(err: AllocationError) FileOpenError { return err; } {#code_end#}But you cannot {#link|coerce|Type Coercion#} an error from a superset to a subset:
{#code_begin|test_err|not a member of destination error set#} const FileOpenError = error { AccessDenied, OutOfMemory, FileNotFound, }; const AllocationError = error { OutOfMemory, }; test "coerce superset to subset" { foo(FileOpenError.OutOfMemory) catch {}; } fn foo(err: FileOpenError) AllocationError { return err; } {#code_end#}There is a shortcut for declaring an error set with only 1 value, and then getting that value:
{#code_begin|syntax#} const err = error.FileNotFound; {#code_end#}This is equivalent to:
{#code_begin|syntax#} const err = (error {FileNotFound}).FileNotFound; {#code_end#}This becomes useful when using {#link|Inferred Error Sets#}.
{#header_open|The Global Error Set#}{#syntax#}anyerror{#endsyntax#} refers to the global error set. This is the error set that contains all errors in the entire compilation unit. It is a superset of all other error sets and a subset of none of them.
You can {#link|coerce|Type Coercion#} any error set to the global one, and you can explicitly cast an error of the global error set to a non-global one. This inserts a language-level assert to make sure the error value is in fact in the destination error set.
The global error set should generally be avoided because it prevents the compiler from knowing what errors are possible at compile-time. Knowing the error set at compile-time is better for generated documentation and helpful error messages, such as forgetting a possible error value in a {#link|switch#}.
{#header_close#} {#header_close#} {#header_open|Error Union Type#}An error set type and normal type can be combined with the {#syntax#}!{#endsyntax#} binary operator to form an error union type. You are likely to use an error union type more often than an error set type by itself.
Here is a function to parse a string into a 64-bit integer:
{#code_begin|test|error_union_parsing_u64#} const std = @import("std"); const maxInt = std.math.maxInt; pub fn parseU64(buf: []const u8, radix: u8) !u64 { var x: u64 = 0; for (buf) |c| { const digit = charToDigit(c); if (digit >= radix) { return error.InvalidChar; } // x *= radix if (@mulWithOverflow(u64, x, radix, &x)) { return error.Overflow; } // x += digit if (@addWithOverflow(u64, x, digit, &x)) { return error.Overflow; } } return x; } fn charToDigit(c: u8) u8 { return switch (c) { '0' ... '9' => c - '0', 'A' ... 'Z' => c - 'A' + 10, 'a' ... 'z' => c - 'a' + 10, else => maxInt(u8), }; } test "parse u64" { const result = try parseU64("1234", 10); try std.testing.expect(result == 1234); } {#code_end#}Notice the return type is {#syntax#}!u64{#endsyntax#}. This means that the function either returns an unsigned 64 bit integer, or an error. We left off the error set to the left of the {#syntax#}!{#endsyntax#}, so the error set is inferred.
Within the function definition, you can see some return statements that return an error, and at the bottom a return statement that returns a {#syntax#}u64{#endsyntax#}. Both types {#link|coerce|Type Coercion#} to {#syntax#}anyerror!u64{#endsyntax#}.
What it looks like to use this function varies depending on what you're trying to do. One of the following:
- You want to provide a default value if it returned an error.
- If it returned an error then you want to return the same error.
- You know with complete certainty it will not return an error, so want to unconditionally unwrap it.
- You want to take a different action for each possible error.
If you want to provide a default value, you can use the {#syntax#}catch{#endsyntax#} binary operator:
{#code_begin|syntax#} const parseU64 = @import("error_union_parsing_u64.zig").parseU64; fn doAThing(str: []u8) void { const number = parseU64(str, 10) catch 13; _ = number; // ... } {#code_end#}In this code, {#syntax#}number{#endsyntax#} will be equal to the successfully parsed string, or a default value of 13. The type of the right hand side of the binary {#syntax#}catch{#endsyntax#} operator must match the unwrapped error union type, or be of type {#syntax#}noreturn{#endsyntax#}.
{#header_close#} {#header_open|try#}Let's say you wanted to return the error if you got one, otherwise continue with the function logic:
{#code_begin|syntax#} const parseU64 = @import("error_union_parsing_u64.zig").parseU64; fn doAThing(str: []u8) !void { const number = parseU64(str, 10) catch |err| return err; _ = number; // ... } {#code_end#}There is a shortcut for this. The {#syntax#}try{#endsyntax#} expression:
{#code_begin|syntax#} const parseU64 = @import("error_union_parsing_u64.zig").parseU64; fn doAThing(str: []u8) !void { const number = try parseU64(str, 10); _ = number; // ... } {#code_end#}{#syntax#}try{#endsyntax#} evaluates an error union expression. If it is an error, it returns from the current function with the same error. Otherwise, the expression results in the unwrapped value.
{#header_close#}Maybe you know with complete certainty that an expression will never be an error. In this case you can do this:
{#syntax#}const number = parseU64("1234", 10) catch unreachable;{#endsyntax#}Here we know for sure that "1234" will parse successfully. So we put the {#syntax#}unreachable{#endsyntax#} value on the right hand side. {#syntax#}unreachable{#endsyntax#} generates a panic in Debug and ReleaseSafe modes and undefined behavior in ReleaseFast mode. So, while we're debugging the application, if there was a surprise error here, the application would crash appropriately.
Finally, you may want to take a different action for every situation. For that, we combine the {#link|if#} and {#link|switch#} expression:
{#syntax_block|zig|handle_all_error_scenarios.zig#} fn doAThing(str: []u8) void { if (parseU64(str, 10)) |number| { doSomethingWithNumber(number); } else |err| switch (err) { error.Overflow => { // handle overflow... }, // we promise that InvalidChar won't happen (or crash in debug mode if it does) error.InvalidChar => unreachable, } } {#end_syntax_block#} {#header_open|errdefer#}The other component to error handling is defer statements. In addition to an unconditional {#link|defer#}, Zig has {#syntax#}errdefer{#endsyntax#}, which evaluates the deferred expression on block exit path if and only if the function returned with an error from the block.
Example:
{#syntax_block|zig|errdefer_example.zig#} fn createFoo(param: i32) !Foo { const foo = try tryToAllocateFoo(); // now we have allocated foo. we need to free it if the function fails. // but we want to return it if the function succeeds. errdefer deallocateFoo(foo); const tmp_buf = allocateTmpBuffer() orelse return error.OutOfMemory; // tmp_buf is truly a temporary resource, and we for sure want to clean it up // before this block leaves scope defer deallocateTmpBuffer(tmp_buf); if (param > 1337) return error.InvalidParam; // here the errdefer will not run since we're returning success from the function. // but the defer will run! return foo; } {#end_syntax_block#}The neat thing about this is that you get robust error handling without the verbosity and cognitive overhead of trying to make sure every exit path is covered. The deallocation code is always directly following the allocation code.
{#header_close#} {#header_open|Common errdefer Slip-Ups#}It should be noted that {#syntax#}errdefer{#endsyntax#} statements only last until the end of the block they are written in, and therefore are not run if an error is returned outside of that block:
{#code_begin|test_err|1 tests leaked memory#} const std = @import("std"); const Allocator = std.mem.Allocator; const Foo = struct { data: u32, }; fn tryToAllocateFoo(allocator: Allocator) !*Foo { return allocator.create(Foo); } fn deallocateFoo(allocator: Allocator, foo: *Foo) void { allocator.destroy(foo); } fn getFooData() !u32 { return 666; } fn createFoo(allocator: Allocator, param: i32) !*Foo { const foo = getFoo: { var foo = try tryToAllocateFoo(allocator); errdefer deallocateFoo(allocator, foo); // Only lasts until the end of getFoo // Calls deallocateFoo on error foo.data = try getFooData(); break :getFoo foo; }; // Outside of the scope of the errdefer, so // deallocateFoo will not be called here if (param > 1337) return error.InvalidParam; return foo; } test "createFoo" { try std.testing.expectError(error.InvalidParam, createFoo(std.testing.allocator, 2468)); } {#code_end#}To ensure that {#syntax#}deallocateFoo{#endsyntax#} is properly called when returning an error, you must add an {#syntax#}errdefer{#endsyntax#} outside of the block: {#code_begin|test|test_errdefer_block#} const std = @import("std"); const Allocator = std.mem.Allocator; const Foo = struct { data: u32, }; fn tryToAllocateFoo(allocator: Allocator) !*Foo { return allocator.create(Foo); } fn deallocateFoo(allocator: Allocator, foo: *Foo) void { allocator.destroy(foo); } fn getFooData() !u32 { return 666; } fn createFoo(allocator: Allocator, param: i32) !*Foo { const foo = getFoo: { var foo = try tryToAllocateFoo(allocator); errdefer deallocateFoo(allocator, foo); foo.data = try getFooData(); break :getFoo foo; }; // This lasts for the rest of the function errdefer deallocateFoo(allocator, foo); // Error is now properly handled by errdefer if (param > 1337) return error.InvalidParam; return foo; } test "createFoo" { try std.testing.expectError(error.InvalidParam, createFoo(std.testing.allocator, 2468)); } {#code_end#}
The fact that errdefers only last for the block they are declared in is especially important when using loops:
{#code_begin|test_err|3 errors were logged#} const std = @import("std"); const Allocator = std.mem.Allocator; const Foo = struct { data: *u32 }; fn getData() !u32 { return 666; } fn genFoos(allocator: Allocator, num: usize) ![]Foo { var foos = try allocator.alloc(Foo, num); errdefer allocator.free(foos); for(foos) |*foo, i| { foo.data = try allocator.create(u32); // This errdefer does not last between iterations errdefer allocator.destroy(foo.data); // The data for the first 3 foos will be leaked if(i >= 3) return error.TooManyFoos; foo.data.* = try getData(); } return foos; } test "genFoos" { try std.testing.expectError(error.TooManyFoos, genFoos(std.testing.allocator, 5)); } {#code_end#}Special care must be taken with code that allocates in a loop to make sure that no memory is leaked when returning an error:
{#code_begin|test|test_errdefer_loop#} const std = @import("std"); const Allocator = std.mem.Allocator; const Foo = struct { data: *u32 }; fn getData() !u32 { return 666; } fn genFoos(allocator: Allocator, num: usize) ![]Foo { var foos = try allocator.alloc(Foo, num); errdefer allocator.free(foos); // Used to track how many foos have been initialized // (including their data being allocated) var num_allocated: usize = 0; errdefer for(foos[0..num_allocated]) |foo| { allocator.destroy(foo.data); }; for(foos) |*foo, i| { foo.data = try allocator.create(u32); num_allocated += 1; if(i >= 3) return error.TooManyFoos; foo.data.* = try getData(); } return foos; } test "genFoos" { try std.testing.expectError(error.TooManyFoos, genFoos(std.testing.allocator, 5)); } {#code_end#} {#header_close#}A couple of other tidbits about error handling:
- These primitives give enough expressiveness that it's completely practical to have failing to check for an error be a compile error. If you really want to ignore the error, you can add {#syntax#}catch unreachable{#endsyntax#} and get the added benefit of crashing in Debug and ReleaseSafe modes if your assumption was wrong.
- Since Zig understands error types, it can pre-weight branches in favor of errors not occurring. Just a small optimization benefit that is not available in other languages.
An error union is created with the {#syntax#}!{#endsyntax#} binary operator. You can use compile-time reflection to access the child type of an error union:
{#code_begin|test|test_error_union#} const expect = @import("std").testing.expect; test "error union" { var foo: anyerror!i32 = undefined; // Coerce from child type of an error union: foo = 1234; // Coerce from an error set: foo = error.SomeError; // Use compile-time reflection to access the payload type of an error union: comptime try expect(@typeInfo(@TypeOf(foo)).ErrorUnion.payload == i32); // Use compile-time reflection to access the error set type of an error union: comptime try expect(@typeInfo(@TypeOf(foo)).ErrorUnion.error_set == anyerror); } {#code_end#} {#header_open|Merging Error Sets#}
Use the {#syntax#}||{#endsyntax#} operator to merge two error sets together. The resulting
error set contains the errors of both error sets. Doc comments from the left-hand
side override doc comments from the right-hand side. In this example, the doc
comments for {#syntax#}C.PathNotFound{#endsyntax#} is A doc comment
.
This is especially useful for functions which return different error sets depending on {#link|comptime#} branches. For example, the Zig standard library uses {#syntax#}LinuxFileOpenError || WindowsFileOpenError{#endsyntax#} for the error set of opening files.
{#code_begin|test|test_merging_error_sets#} const A = error{ NotDir, /// A doc comment PathNotFound, }; const B = error{ OutOfMemory, /// B doc comment PathNotFound, }; const C = A || B; fn foo() C!void { return error.NotDir; } test "merge error sets" { if (foo()) { @panic("unexpected"); } else |err| switch (err) { error.OutOfMemory => @panic("unexpected"), error.PathNotFound => @panic("unexpected"), error.NotDir => {}, } } {#code_end#} {#header_close#} {#header_open|Inferred Error Sets#}Because many functions in Zig return a possible error, Zig supports inferring the error set. To infer the error set for a function, prepend the {#syntax#}!{#endsyntax#} operator to the function’s return type, like {#syntax#}!T{#endsyntax#}:
{#code_begin|test|inferred_error_sets#} // With an inferred error set pub fn add_inferred(comptime T: type, a: T, b: T) !T { var answer: T = undefined; return if (@addWithOverflow(T, a, b, &answer)) error.Overflow else answer; } // With an explicit error set pub fn add_explicit(comptime T: type, a: T, b: T) Error!T { var answer: T = undefined; return if (@addWithOverflow(T, a, b, &answer)) error.Overflow else answer; } const Error = error { Overflow, }; const std = @import("std"); test "inferred error set" { if (add_inferred(u8, 255, 1)) |_| unreachable else |err| switch (err) { error.Overflow => {}, // ok } } {#code_end#}When a function has an inferred error set, that function becomes generic and thus it becomes trickier to do certain things with it, such as obtain a function pointer, or have an error set that is consistent across different build targets. Additionally, inferred error sets are incompatible with recursion.
In these situations, it is recommended to use an explicit error set. You can generally start with an empty error set and let compile errors guide you toward completing the set.
These limitations may be overcome in a future version of Zig.
{#header_close#} {#header_close#} {#header_open|Error Return Traces#}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.
{#code_begin|exe_err#} pub fn main() !void { try foo(12); } fn foo(x: i32) !void { if (x >= 5) { try bar(); } else { try bang2(); } } fn bar() !void { if (baz()) { try quux(); } else |err| switch (err) { error.FileNotFound => try hello(), } } fn baz() !void { try bang1(); } fn quux() !void { try bang2(); } fn hello() !void { try bang2(); } fn bang1() !void { return error.FileNotFound; } fn bang2() !void { return error.PermissionDenied; } {#code_end#}Look closely at this example. This is no stack trace.
You can see that the final error bubbled up was {#syntax#}PermissionDenied{#endsyntax#}, 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, and then returns another one, from the switch statement. Error Return Traces make this clear, whereas a stack trace would look like this:
{#code_begin|exe_err#} pub fn main() void { foo(12); } fn foo(x: i32) void { if (x >= 5) { bar(); } else { bang2(); } } fn bar() void { if (baz()) { quux(); } else { hello(); } } fn baz() bool { return bang1(); } fn quux() void { bang2(); } fn hello() void { bang2(); } fn bang1() bool { return false; } fn bang2() void { @panic("PermissionDenied"); } {#code_end#}Here, the stack trace does not explain how the control flow in {#syntax#}bar{#endsyntax#} got to the {#syntax#}hello(){#endsyntax#} call. One would have to open a debugger or further instrument the application in order to find out. The error return trace, on the other hand, shows exactly how the error bubbled up.
This debugging feature makes it easier to iterate quickly on code that robustly handles all error conditions. This means that Zig developers will naturally find themselves writing correct, robust code in order to increase their development pace.
Error Return Traces are enabled by default in {#link|Debug#} and {#link|ReleaseSafe#} builds and disabled by default in {#link|ReleaseFast#} and {#link|ReleaseSmall#} builds.
There are a few ways to activate this error return tracing feature:
- Return an error from main
- An error makes its way to {#syntax#}catch unreachable{#endsyntax#} and you have not overridden the default panic handler
- Use {#link|errorReturnTrace#} to access the current return trace. You can use {#syntax#}std.debug.dumpStackTrace{#endsyntax#} to print it. This function returns comptime-known {#link|null#} when building without error return tracing support.
To analyze performance cost, there are two cases:
- when no errors are returned
- when returning errors
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#}. This is to initialize this struct in the stack memory:
{#syntax_block|zig|stack_trace_struct.zig#} pub const StackTrace = struct { index: usize, instruction_addresses: [N]usize, }; {#end_syntax_block#}Here, N is the maximum function call depth as determined by call graph analysis. Recursion is ignored and counts for 2.
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.
That's it for the path when no errors occur. It's practically free in terms of performance.
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:
{#syntax_block|zig|zig_return_error_fn.zig#} // marked as "no-inline" in LLVM IR fn __zig_return_error(stack_trace: *StackTrace) void { stack_trace.instruction_addresses[stack_trace.index] = @returnAddress(); stack_trace.index = (stack_trace.index + 1) % N; } {#end_syntax_block#}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.
As for code size cost, 1 function call before a return statement is no big deal. Even so, I have a plan to make the call to {#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.
{#header_close#} {#header_close#} {#header_close#} {#header_open|Optionals#}One area that Zig provides safety without compromising efficiency or readability is with the optional type.
The question mark symbolizes the optional type. You can convert a type to an optional type by putting a question mark in front of it, like this:
{#code_begin|syntax#} // normal integer const normal_int: i32 = 1234; // optional integer const optional_int: ?i32 = 5678; {#code_end#}Now the variable {#syntax#}optional_int{#endsyntax#} could be an {#syntax#}i32{#endsyntax#}, or {#syntax#}null{#endsyntax#}.
Instead of integers, let's talk about pointers. Null references are the source of many runtime exceptions, and even stand accused of being the worst mistake of computer science.
Zig does not have them.
Instead, you can use an optional pointer. This secretly compiles down to a normal pointer, since we know we can use 0 as the null value for the optional type. But the compiler can check your work and make sure you don't assign null to something that can't be null.
Typically the downside of not having null is that it makes the code more verbose to write. But, let's compare some equivalent C code and Zig code.
Task: call malloc, if the result is null, return null.
C code
{#syntax_block|c|call_malloc_in_c.c#}// malloc prototype included for reference void *malloc(size_t size); struct Foo *do_a_thing(void) { char *ptr = malloc(1234); if (!ptr) return NULL; // ... }{#end_syntax_block#}Zig code
{#syntax_block|zig|call_malloc_from_zig.zig#} // malloc prototype included for reference extern fn malloc(size: size_t) ?*u8; fn doAThing() ?*Foo { const ptr = malloc(1234) orelse return null; _ = ptr; // ... } {#end_syntax_block#}Here, Zig is at least as convenient, if not more, than C. And, the type of "ptr" is {#syntax#}*u8{#endsyntax#} not {#syntax#}?*u8{#endsyntax#}. The {#syntax#}orelse{#endsyntax#} keyword unwrapped the optional type and therefore {#syntax#}ptr{#endsyntax#} is guaranteed to be non-null everywhere it is used in the function.
The other form of checking against NULL you might see looks like this:
{#syntax_block|c|checking_null_in_c.c#}void do_a_thing(struct Foo *foo) { // do some stuff if (foo) { do_something_with_foo(foo); } // do some stuff }{#end_syntax_block#}In Zig you can accomplish the same thing:
{#code_begin|syntax|checking_null_in_zig#} const Foo = struct{}; fn doSomethingWithFoo(foo: *Foo) void { _ = foo; } fn doAThing(optional_foo: ?*Foo) void { // do some stuff if (optional_foo) |foo| { doSomethingWithFoo(foo); } // do some stuff } {#code_end#}Once again, the notable thing here is that inside the if block, {#syntax#}foo{#endsyntax#} is no longer an optional pointer, it is a pointer, which cannot be null.
One benefit to this is that functions which take pointers as arguments can
be annotated with the "nonnull" attribute - __attribute__((nonnull))
in
GCC.
The optimizer can sometimes make better decisions knowing that pointer arguments
cannot be null.
An optional is created by putting {#syntax#}?{#endsyntax#} in front of a type. You can use compile-time reflection to access the child type of an optional:
{#code_begin|test|test_optional_type#} const expect = @import("std").testing.expect; test "optional type" { // Declare an optional and coerce from null: var foo: ?i32 = null; // Coerce from child type of an optional foo = 1234; // Use compile-time reflection to access the child type of the optional: comptime try expect(@typeInfo(@TypeOf(foo)).Optional.child == i32); } {#code_end#} {#header_close#} {#header_open|null#}Just like {#link|undefined#}, {#syntax#}null{#endsyntax#} has its own type, and the only way to use it is to cast it to a different type:
{#code_begin|syntax#} const optional_value: ?i32 = null; {#code_end#} {#header_close#} {#header_open|Optional Pointers#}An optional pointer is guaranteed to be the same size as a pointer. The {#syntax#}null{#endsyntax#} of the optional is guaranteed to be address 0.
{#code_begin|test|test_optional_pointer#} const expect = @import("std").testing.expect; test "optional pointers" { // Pointers cannot be null. If you want a null pointer, use the optional // prefix `?` to make the pointer type optional. var ptr: ?*i32 = null; var x: i32 = 1; ptr = &x; try expect(ptr.?.* == 1); // Optional pointers are the same size as normal pointers, because pointer // value 0 is used as the null value. try expect(@sizeOf(?*i32) == @sizeOf(*i32)); } {#code_end#} {#header_close#} {#header_close#} {#header_open|Casting#}A type cast converts a value of one type to another. Zig has {#link|Type Coercion#} for conversions that are known to be completely safe and unambiguous, and {#link|Explicit Casts#} for conversions that one would not want to happen on accident. There is also a third kind of type conversion called {#link|Peer Type Resolution#} for the case when a result type must be decided given multiple operand types.
{#header_open|Type Coercion#}Type coercion occurs when one type is expected, but different type is provided:
{#code_begin|test|type_coercion#} test "type coercion - variable declaration" { var a: u8 = 1; var b: u16 = a; _ = b; } test "type coercion - function call" { var a: u8 = 1; foo(a); } fn foo(b: u16) void { _ = b; } test "type coercion - @as builtin" { var a: u8 = 1; var b = @as(u16, a); _ = b; } {#code_end#}Type coercions are only allowed when it is completely unambiguous how to get from one type to another, and the transformation is guaranteed to be safe. There is one exception, which is {#link|C Pointers#}.
{#header_open|Type Coercion: Stricter Qualification#}Values which have the same representation at runtime can be cast to increase the strictness of the qualifiers, no matter how nested the qualifiers are:
- {#syntax#}const{#endsyntax#} - non-const to const is allowed
- {#syntax#}volatile{#endsyntax#} - non-volatile to volatile is allowed
- {#syntax#}align{#endsyntax#} - bigger to smaller alignment is allowed
- {#link|error sets|Error Set Type#} to supersets is allowed
These casts are no-ops at runtime since the value representation does not change.
{#code_begin|test|no_op_casts#} test "type coercion - const qualification" { var a: i32 = 1; var b: *i32 = &a; foo(b); } fn foo(_: *const i32) void {} {#code_end#}In addition, pointers coerce to const optional pointers:
{#code_begin|test|pointer_coerce_const_optional#} const std = @import("std"); const expect = std.testing.expect; const mem = std.mem; test "cast *[1][*]const u8 to [*]const ?[*]const u8" { const window_name = [1][*]const u8{"window name"}; const x: [*]const ?[*]const u8 = &window_name; try expect(mem.eql(u8, std.mem.sliceTo(@ptrCast([*:0]const u8, x[0].?), 0), "window name")); } {#code_end#} {#header_close#} {#header_open|Type Coercion: Integer and Float Widening#}{#link|Integers#} coerce to integer types which can represent every value of the old type, and likewise {#link|Floats#} coerce to float types which can represent every value of the old type.
{#code_begin|test|test_integer_widening#} const std = @import("std"); const builtin = @import("builtin"); const expect = std.testing.expect; const mem = std.mem; test "integer widening" { var a: u8 = 250; var b: u16 = a; var c: u32 = b; var d: u64 = c; var e: u64 = d; var f: u128 = e; try expect(f == a); } test "implicit unsigned integer to signed integer" { var a: u8 = 250; var b: i16 = a; try expect(b == 250); } test "float widening" { // Note: there is an open issue preventing this from working on aarch64: // https://github.com/ziglang/zig/issues/3282 if (builtin.target.cpu.arch == .aarch64) return error.SkipZigTest; var a: f16 = 12.34; var b: f32 = a; var c: f64 = b; var d: f128 = c; try expect(d == a); } {#code_end#} {#header_close#} {#header_open|Type Coercion: Coercion Float to Int#}A compiler error is appropriate because this ambiguous expression leaves the compiler two choices about the coercion.
- 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#}
- 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#}
The payload type of {#link|Optionals#}, as well as {#link|null#}, coerce to the optional type.
{#code_begin|test|test_coerce_optionals#} const std = @import("std"); const expect = std.testing.expect; test "coerce to optionals" { const x: ?i32 = 1234; const y: ?i32 = null; try expect(x.? == 1234); try expect(y == null); } {#code_end#}It works nested inside the {#link|Error Union Type#}, too:
{#code_begin|test|test_coerce_optional_wrapped_error_union#} const std = @import("std"); const expect = std.testing.expect; test "coerce to optionals wrapped in error union" { const x: anyerror!?i32 = 1234; const y: anyerror!?i32 = null; try expect((try x).? == 1234); try expect((try y) == null); } {#code_end#} {#header_close#} {#header_open|Type Coercion: Error Unions#}The payload type of an {#link|Error Union Type#} as well as the {#link|Error Set Type#} coerce to the error union type:
{#code_begin|test|test_coerce_to_error_union#} const std = @import("std"); const expect = std.testing.expect; test "coercion to error unions" { const x: anyerror!i32 = 1234; const y: anyerror!i32 = error.Failure; try expect((try x) == 1234); try std.testing.expectError(error.Failure, y); } {#code_end#} {#header_close#} {#header_open|Type Coercion: Compile-Time Known Numbers#}When a number is {#link|comptime#}-known to be representable in the destination type, it may be coerced:
{#code_begin|test|test_coerce_large_to_small#} const std = @import("std"); const expect = std.testing.expect; test "coercing large integer type to smaller one when value is comptime known to fit" { const x: u64 = 255; const y: u8 = x; try expect(y == 255); } {#code_end#} {#header_close#} {#header_open|Type Coercion: unions and enums#}Tagged unions can be coerced to enums, and enums can be coerced to tagged unions when they are {#link|comptime#}-known to be a field of the union that has only one possible value, such as {#link|void#}:
{#code_begin|test|test_coerce_unions_enums#} const std = @import("std"); const expect = std.testing.expect; const E = enum { one, two, three, }; const U = union(E) { one: i32, two: f32, three, }; test "coercion between unions and enums" { var u = U{ .two = 12.34 }; var e: E = u; try expect(e == E.two); const three = E.three; var another_u: U = three; try expect(another_u == E.three); } {#code_end#} {#see_also|union|enum#} {#header_close#} {#header_open|Type Coercion: undefined#}{#link|undefined#} can be cast to any type.
{#header_close#} {#header_close#} {#header_open|Explicit Casts#}Explicit casts are performed via {#link|Builtin Functions#}. Some explicit casts are safe; some are not. Some explicit casts perform language-level assertions; some do not. Some explicit casts are no-ops at runtime; some are not.
- {#link|@bitCast#} - change type but maintain bit representation
- {#link|@alignCast#} - make a pointer have more alignment
- {#link|@boolToInt#} - convert true to 1 and false to 0
- {#link|@enumToInt#} - obtain the integer tag value of an enum or tagged union
- {#link|@errSetCast#} - convert to a smaller error set
- {#link|@errorToInt#} - obtain the integer value of an error code
- {#link|@floatCast#} - convert a larger float to a smaller float
- {#link|@floatToInt#} - obtain the integer part of a float value
- {#link|@intCast#} - convert between integer types
- {#link|@intToEnum#} - obtain an enum value based on its integer tag value
- {#link|@intToError#} - obtain an error code based on its integer value
- {#link|@intToFloat#} - convert an integer to a float value
- {#link|@intToPtr#} - convert an address to a pointer
- {#link|@ptrCast#} - convert between pointer types
- {#link|@ptrToInt#} - obtain the address of a pointer
- {#link|@truncate#} - convert between integer types, chopping off bits
Peer Type Resolution occurs in these places:
- {#link|switch#} expressions
- {#link|if#} expressions
- {#link|while#} expressions
- {#link|for#} expressions
- Multiple break statements in a block
- Some {#link|binary operations|Table of Operators#}
This kind of type resolution chooses a type that all peer types can coerce into. Here are some examples:
{#code_begin|test|peer_type_resolution#} const std = @import("std"); const expect = std.testing.expect; const mem = std.mem; test "peer resolve int widening" { var a: i8 = 12; var b: i16 = 34; var c = a + b; try expect(c == 46); try expect(@TypeOf(c) == i16); } test "peer resolve arrays of different size to const slice" { try expect(mem.eql(u8, boolToStr(true), "true")); try expect(mem.eql(u8, boolToStr(false), "false")); comptime try expect(mem.eql(u8, boolToStr(true), "true")); comptime try expect(mem.eql(u8, boolToStr(false), "false")); } fn boolToStr(b: bool) []const u8 { return if (b) "true" else "false"; } test "peer resolve array and const slice" { try testPeerResolveArrayConstSlice(true); comptime try testPeerResolveArrayConstSlice(true); } fn testPeerResolveArrayConstSlice(b: bool) !void { const value1 = if (b) "aoeu" else @as([]const u8, "zz"); const value2 = if (b) @as([]const u8, "zz") else "aoeu"; try expect(mem.eql(u8, value1, "aoeu")); try expect(mem.eql(u8, value2, "zz")); } test "peer type resolution: ?T and T" { try expect(peerTypeTAndOptionalT(true, false).? == 0); try expect(peerTypeTAndOptionalT(false, false).? == 3); comptime { try expect(peerTypeTAndOptionalT(true, false).? == 0); try expect(peerTypeTAndOptionalT(false, false).? == 3); } } fn peerTypeTAndOptionalT(c: bool, b: bool) ?usize { if (c) { return if (b) null else @as(usize, 0); } return @as(usize, 3); } test "peer type resolution: *[0]u8 and []const u8" { try expect(peerTypeEmptyArrayAndSlice(true, "hi").len == 0); try expect(peerTypeEmptyArrayAndSlice(false, "hi").len == 1); comptime { try expect(peerTypeEmptyArrayAndSlice(true, "hi").len == 0); try expect(peerTypeEmptyArrayAndSlice(false, "hi").len == 1); } } fn peerTypeEmptyArrayAndSlice(a: bool, slice: []const u8) []const u8 { if (a) { return &[_]u8{}; } return slice[0..1]; } test "peer type resolution: *[0]u8, []const u8, and anyerror![]u8" { { var data = "hi".*; const slice = data[0..]; try expect((try peerTypeEmptyArrayAndSliceAndError(true, slice)).len == 0); try expect((try peerTypeEmptyArrayAndSliceAndError(false, slice)).len == 1); } comptime { var data = "hi".*; const slice = data[0..]; try expect((try peerTypeEmptyArrayAndSliceAndError(true, slice)).len == 0); try expect((try peerTypeEmptyArrayAndSliceAndError(false, slice)).len == 1); } } fn peerTypeEmptyArrayAndSliceAndError(a: bool, slice: []u8) anyerror![]u8 { if (a) { return &[_]u8{}; } return slice[0..1]; } test "peer type resolution: *const T and ?*T" { const a = @intToPtr(*const usize, 0x123456780); const b = @intToPtr(?*usize, 0x123456780); try expect(a == b); try expect(b == a); } {#code_end#} {#header_close#} {#header_close#} {#header_open|Zero Bit Types#}For some types, {#link|@sizeOf#} is 0:
- {#link|void#}
- The {#link|Integers#} {#syntax#}u0{#endsyntax#} and {#syntax#}i0{#endsyntax#}.
- {#link|Arrays#} and {#link|Vectors#} with len 0, or with an element type that is a zero bit type.
- An {#link|enum#} with only 1 tag.
- A {#link|struct#} with all fields being zero bit types.
- A {#link|union#} with only 1 field which is a zero bit type.
These types can only ever have one possible value, and thus require 0 bits to represent. Code that makes use of these types is not included in the final generated code:
{#code_begin|syntax#} export fn entry() void { var x: void = {}; var y: void = {}; x = y; } {#code_end#}When this turns into machine code, there is no code generated in the body of {#syntax#}entry{#endsyntax#}, even in {#link|Debug#} mode. For example, on x86_64:
0000000000000010 <entry>:
10: 55 push %rbp
11: 48 89 e5 mov %rsp,%rbp
14: 5d pop %rbp
15: c3 retq
These assembly instructions do not have any code associated with the void values - they only perform the function call prologue and epilogue.
{#header_open|void#}{#syntax#}void{#endsyntax#} can be useful for instantiating generic types. For example, given a {#syntax#}Map(Key, Value){#endsyntax#}, one can pass {#syntax#}void{#endsyntax#} for the {#syntax#}Value{#endsyntax#} type to make it into a {#syntax#}Set{#endsyntax#}:
{#code_begin|test|void_in_hashmap#} const std = @import("std"); const expect = std.testing.expect; test "turn HashMap into a set with void" { var map = std.AutoHashMap(i32, void).init(std.testing.allocator); defer map.deinit(); try map.put(1, {}); try map.put(2, {}); try expect(map.contains(2)); try expect(!map.contains(3)); _ = map.remove(2); try expect(!map.contains(2)); } {#code_end#}Note that this is different from using a dummy value for the hash map value. By using {#syntax#}void{#endsyntax#} as the type of the value, the hash map entry type has no value field, and thus the hash map takes up less space. Further, all the code that deals with storing and loading the value is deleted, as seen above.
{#syntax#}void{#endsyntax#} is distinct from {#syntax#}anyopaque{#endsyntax#}. {#syntax#}void{#endsyntax#} has a known size of 0 bytes, and {#syntax#}anyopaque{#endsyntax#} has an unknown, but non-zero, size.
Expressions of type {#syntax#}void{#endsyntax#} are the only ones whose value can be ignored. For example:
{#code_begin|test_err|ignored#} test "ignoring expression value" { foo(); } fn foo() i32 { return 1234; } {#code_end#}However, if the expression has type {#syntax#}void{#endsyntax#}, there will be no error. Function return values can also be explicitly ignored by assigning them to {#syntax#}_{#endsyntax#}.
{#code_begin|test|void_ignored#} test "void is ignored" { returnsVoid(); } test "explicitly ignoring expression value" { _ = foo(); } fn returnsVoid() void {} fn foo() i32 { return 1234; } {#code_end#} {#header_close#} {#header_close#} {#header_open|Result Location Semantics#}TODO add documentation for this
{#header_close#} {#header_open|usingnamespace#}{#syntax#}usingnamespace{#endsyntax#} is a declaration that mixes all the public declarations of the operand, which must be a {#link|struct#}, {#link|union#}, {#link|enum#}, or {#link|opaque#}, into the namespace:
{#code_begin|test|usingnamespace#} test "using std namespace" { const S = struct { usingnamespace @import("std"); }; try S.testing.expect(true); } {#code_end#}
{#syntax#}usingnamespace{#endsyntax#} has an important use case when organizing the public
API of a file or package. For example, one might have c.zig
with all of the
{#link|C imports|Import from C Header File#}:
The above example demonstrates using {#syntax#}pub{#endsyntax#} to qualify the {#syntax#}usingnamespace{#endsyntax#} additionally makes the imported declarations {#syntax#}pub{#endsyntax#}. This can be used to forward declarations, giving precise control over what declarations a given file exposes.
{#header_close#} {#header_open|comptime#}Zig places importance on the concept of whether an expression is known at compile-time. There are a few different places this concept is used, and these building blocks are used to keep the language small, readable, and powerful.
{#header_open|Introducing the Compile-Time Concept#} {#header_open|Compile-Time Parameters#}Compile-time parameters is how Zig implements generics. It is compile-time duck typing.
{#code_begin|syntax#} fn max(comptime T: type, a: T, b: T) T { return if (a > b) a else b; } fn gimmeTheBiggerFloat(a: f32, b: f32) f32 { return max(f32, a, b); } fn gimmeTheBiggerInteger(a: u64, b: u64) u64 { return max(u64, a, b); } {#code_end#}In Zig, types are first-class citizens. They can be assigned to variables, passed as parameters to functions, and returned from functions. However, they can only be used in expressions which are known at compile-time, which is why the parameter {#syntax#}T{#endsyntax#} in the above snippet must be marked with {#syntax#}comptime{#endsyntax#}.
A {#syntax#}comptime{#endsyntax#} parameter means that:
- At the callsite, the value must be known at compile-time, or it is a compile error.
- In the function definition, the value is known at compile-time.
For example, if we were to introduce another function to the above snippet:
{#code_begin|test_err|unable to resolve comptime value#} fn max(comptime T: type, a: T, b: T) T { return if (a > b) a else b; } test "try to pass a runtime type" { foo(false); } fn foo(condition: bool) void { const result = max( if (condition) f32 else u64, 1234, 5678); _ = result; } {#code_end#}This is an error because the programmer attempted to pass a value only known at run-time to a function which expects a value known at compile-time.
Another way to get an error is if we pass a type that violates the type checker when the function is analyzed. This is what it means to have compile-time duck typing.
For example:
{#code_begin|test_err|operator > not allowed for type 'bool'#} fn max(comptime T: type, a: T, b: T) T { return if (a > b) a else b; } test "try to compare bools" { _ = max(bool, true, false); } {#code_end#}On the flip side, inside the function definition with the {#syntax#}comptime{#endsyntax#} parameter, the value is known at compile-time. This means that we actually could make this work for the bool type if we wanted to:
{#code_begin|test|comptime_max_with_bool#} fn max(comptime T: type, a: T, b: T) T { if (T == bool) { return a or b; } else if (a > b) { return a; } else { return b; } } test "try to compare bools" { try @import("std").testing.expect(max(bool, false, true) == true); } {#code_end#}This works because Zig implicitly inlines {#syntax#}if{#endsyntax#} expressions when the condition is known at compile-time, and the compiler guarantees that it will skip analysis of the branch not taken.
This means that the actual function generated for {#syntax#}max{#endsyntax#} in this situation looks like this:
{#code_begin|syntax#} fn max(a: bool, b: bool) bool { return a or b; } {#code_end#}All the code that dealt with compile-time known values is eliminated and we are left with only the necessary run-time code to accomplish the task.
This works the same way for {#syntax#}switch{#endsyntax#} expressions - they are implicitly inlined when the target expression is compile-time known.
{#header_close#} {#header_open|Compile-Time Variables#}In Zig, the programmer can label variables as {#syntax#}comptime{#endsyntax#}. This guarantees to the compiler that every load and store of the variable is performed at compile-time. Any violation of this results in a compile error.
This combined with the fact that we can {#syntax#}inline{#endsyntax#} loops allows us to write a function which is partially evaluated at compile-time and partially at run-time.
For example:
{#code_begin|test|comptime_vars#} const expect = @import("std").testing.expect; const CmdFn = struct { name: []const u8, func: fn(i32) i32, }; const cmd_fns = [_]CmdFn{ CmdFn {.name = "one", .func = one}, CmdFn {.name = "two", .func = two}, CmdFn {.name = "three", .func = three}, }; fn one(value: i32) i32 { return value + 1; } fn two(value: i32) i32 { return value + 2; } fn three(value: i32) i32 { return value + 3; } fn performFn(comptime prefix_char: u8, start_value: i32) i32 { var result: i32 = start_value; comptime var i = 0; inline while (i < cmd_fns.len) : (i += 1) { if (cmd_fns[i].name[0] == prefix_char) { result = cmd_fns[i].func(result); } } return result; } test "perform fn" { try expect(performFn('t', 1) == 6); try expect(performFn('o', 0) == 1); try expect(performFn('w', 99) == 99); } {#code_end#}This example is a bit contrived, because the compile-time evaluation component is unnecessary; this code would work fine if it was all done at run-time. But it does end up generating different code. In this example, the function {#syntax#}performFn{#endsyntax#} is generated three different times, for the different values of {#syntax#}prefix_char{#endsyntax#} provided:
{#syntax_block|zig|performFn_1#} // From the line: // expect(performFn('t', 1) == 6); fn performFn(start_value: i32) i32 { var result: i32 = start_value; result = two(result); result = three(result); return result; } {#end_syntax_block#} {#syntax_block|zig|performFn_2#} // From the line: // expect(performFn('o', 0) == 1); fn performFn(start_value: i32) i32 { var result: i32 = start_value; result = one(result); return result; } {#end_syntax_block#} {#syntax_block|zig|performFn_3#} // From the line: // expect(performFn('w', 99) == 99); fn performFn(start_value: i32) i32 { var result: i32 = start_value; return result; } {#end_syntax_block#}Note that this happens even in a debug build; in a release build these generated functions still pass through rigorous LLVM optimizations. The important thing to note, however, is not that this is a way to write more optimized code, but that it is a way to make sure that what should happen at compile-time, does happen at compile-time. This catches more errors and as demonstrated later in this article, allows expressiveness that in other languages requires using macros, generated code, or a preprocessor to accomplish.
{#header_close#} {#header_open|Compile-Time Expressions#}In Zig, it matters whether a given expression is known at compile-time or run-time. A programmer can use a {#syntax#}comptime{#endsyntax#} expression to guarantee that the expression will be evaluated at compile-time. If this cannot be accomplished, the compiler will emit an error. For example:
{#code_begin|test_err|comptime call of extern function#} extern fn exit() noreturn; test "foo" { comptime { exit(); } } {#code_end#}It doesn't make sense that a program could call {#syntax#}exit(){#endsyntax#} (or any other external function) at compile-time, so this is a compile error. However, a {#syntax#}comptime{#endsyntax#} expression does much more than sometimes cause a compile error.
Within a {#syntax#}comptime{#endsyntax#} expression:
- All variables are {#syntax#}comptime{#endsyntax#} variables.
- All {#syntax#}if{#endsyntax#}, {#syntax#}while{#endsyntax#}, {#syntax#}for{#endsyntax#}, and {#syntax#}switch{#endsyntax#} expressions are evaluated at compile-time, or emit a compile error if this is not possible.
- All function calls cause the compiler to interpret the function at compile-time, emitting a compile error if the function tries to do something that has global run-time side effects.
This means that a programmer can create a function which is called both at compile-time and run-time, with no modification to the function required.
Let's look at an example:
{#code_begin|test|fibonacci_recursion#} const expect = @import("std").testing.expect; fn fibonacci(index: u32) u32 { if (index < 2) return index; return fibonacci(index - 1) + fibonacci(index - 2); } test "fibonacci" { // test fibonacci at run-time try expect(fibonacci(7) == 13); // test fibonacci at compile-time comptime { try expect(fibonacci(7) == 13); } } {#code_end#}Imagine if we had forgotten the base case of the recursive function and tried to run the tests:
{#code_begin|test_err|overflow of integer type#} const expect = @import("std").testing.expect; fn fibonacci(index: u32) u32 { //if (index < 2) return index; return fibonacci(index - 1) + fibonacci(index - 2); } test "fibonacci" { comptime { try expect(fibonacci(7) == 13); } } {#code_end#}The compiler produces an error which is a stack trace from trying to evaluate the function at compile-time.
Luckily, we used an unsigned integer, and so when we tried to subtract 1 from 0, it triggered undefined behavior, which is always a compile error if the compiler knows it happened. But what would have happened if we used a signed integer?
{#code_begin|test_err|evaluation exceeded 1000 backwards branches#} {#backend_stage1#} const assert = @import("std").debug.assert; fn fibonacci(index: i32) i32 { //if (index < 2) return index; return fibonacci(index - 1) + fibonacci(index - 2); } test "fibonacci" { comptime { try assert(fibonacci(7) == 13); } } {#code_end#}The compiler noticed that evaluating this function at compile-time took a long time, and thus emitted a compile error and gave up. If the programmer wants to increase the budget for compile-time computation, they can use a built-in function called {#link|@setEvalBranchQuota#} to change the default number 1000 to something else.
What if we fix the base case, but put the wrong value in the {#syntax#}expect{#endsyntax#} line?
{#code_begin|test_err|reached unreachable#} const assert = @import("std").debug.assert; fn fibonacci(index: i32) i32 { if (index < 2) return index; return fibonacci(index - 1) + fibonacci(index - 2); } test "fibonacci" { comptime { try assert(fibonacci(7) == 99999); } } {#code_end#}At {#link|container|Containers#} level (outside of any function), all expressions are implicitly {#syntax#}comptime{#endsyntax#} expressions. This means that we can use functions to initialize complex static data. For example:
{#code_begin|test|N_primes#} const first_25_primes = firstNPrimes(25); const sum_of_first_25_primes = sum(&first_25_primes); fn firstNPrimes(comptime n: usize) [n]i32 { var prime_list: [n]i32 = undefined; var next_index: usize = 0; var test_number: i32 = 2; while (next_index < prime_list.len) : (test_number += 1) { var test_prime_index: usize = 0; var is_prime = true; while (test_prime_index < next_index) : (test_prime_index += 1) { if (test_number % prime_list[test_prime_index] == 0) { is_prime = false; break; } } if (is_prime) { prime_list[next_index] = test_number; next_index += 1; } } return prime_list; } fn sum(numbers: []const i32) i32 { var result: i32 = 0; for (numbers) |x| { result += x; } return result; } test "variable values" { try @import("std").testing.expect(sum_of_first_25_primes == 1060); } {#code_end#}When we compile this program, Zig generates the constants with the answer pre-computed. Here are the lines from the generated LLVM IR:
@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]
@1 = internal unnamed_addr constant i32 1060
Note that we did not have to do anything special with the syntax of these functions. For example, we could call the {#syntax#}sum{#endsyntax#} function as is with a slice of numbers whose length and values were only known at run-time.
{#header_close#} {#header_close#} {#header_open|Generic Data Structures#}Zig uses these capabilities to implement generic data structures without introducing any special-case syntax. If you followed along so far, you may already know how to create a generic data structure.
Here is an example of a generic {#syntax#}List{#endsyntax#} data structure.
{#code_begin|syntax#} fn List(comptime T: type) type { return struct { items: []T, len: usize, }; } // The generic List data structure can be instantiated by passing in a type: var buffer: [10]i32 = undefined; var list = List(i32){ .items = &buffer, .len = 0, }; {#code_end#}That's it. It's a function that returns an anonymous {#syntax#}struct{#endsyntax#}. To keep the language small and uniform, all aggregate types in Zig are anonymous. For the purposes of error messages and debugging, Zig infers the name {#syntax#}"List(i32)"{#endsyntax#} from the function name and parameters invoked when creating the anonymous struct.
To explicitly give a type a name, we assign it to a constant.
{#code_begin|syntax#} const Node = struct { next: ?*Node, name: []const u8, }; var node_a = Node{ .next = null, .name = &"Node A", }; var node_b = Node{ .next = &node_a, .name = &"Node B", }; {#code_end#}In this example, the {#syntax#}Node{#endsyntax#} struct refers to itself. This works because all top level declarations are order-independent. As long as the compiler can determine the size of the struct, it is free to refer to itself. In this case, {#syntax#}Node{#endsyntax#} refers to itself as a pointer, which has a well-defined size at compile time, so it works fine.
{#header_close#} {#header_open|Case Study: print in Zig#}Putting all of this together, let's see how {#syntax#}print{#endsyntax#} works in Zig.
{#code_begin|exe|print#} const print = @import("std").debug.print; const a_number: i32 = 1234; const a_string = "foobar"; pub fn main() void { print("here is a string: '{s}' here is a number: {}\n", .{a_string, a_number}); } {#code_end#}Let's crack open the implementation of this and see how it works:
{#code_begin|syntax|poc_print_fn#} const Writer = struct { /// Calls print and then flushes the buffer. pub fn print(self: *Writer, comptime format: []const u8, args: anytype) anyerror!void { const State = enum { start, open_brace, close_brace, }; comptime var start_index: usize = 0; comptime var state = State.start; comptime var next_arg: usize = 0; inline for (format) |c, i| { switch (state) { State.start => switch (c) { '{' => { if (start_index < i) try self.write(format[start_index..i]); state = State.open_brace; }, '}' => { if (start_index < i) try self.write(format[start_index..i]); state = State.close_brace; }, else => {}, }, State.open_brace => switch (c) { '{' => { state = State.start; start_index = i; }, '}' => { try self.printValue(args[next_arg]); next_arg += 1; state = State.start; start_index = i + 1; }, 's' => { continue; }, else => @compileError("Unknown format character: " ++ [1]u8{c}), }, State.close_brace => switch (c) { '}' => { state = State.start; start_index = i; }, else => @compileError("Single '}' encountered in format string"), }, } } comptime { if (args.len != next_arg) { @compileError("Unused arguments"); } if (state != State.start) { @compileError("Incomplete format string: " ++ format); } } if (start_index < format.len) { try self.write(format[start_index..format.len]); } try self.flush(); } fn write(self: *Writer, value: []const u8) !void { _ = self; _ = value; } pub fn printValue(self: *Writer, value: anytype) !void { _ = self; _ = value; } fn flush(self: *Writer) !void { _ = self; } }; {#code_end#}This is a proof of concept implementation; the actual function in the standard library has more formatting capabilities.
Note that this is not hard-coded into the Zig compiler; this is userland code in the standard library.
When this function is analyzed from our example code above, Zig partially evaluates the function and emits a function that actually looks like this:
{#syntax_block|zig|Emitted print Function#} pub fn print(self: *Writer, arg0: []const u8, arg1: i32) !void { try self.write("here is a string: '"); try self.printValue(arg0); try self.write("' here is a number: "); try self.printValue(arg1); try self.write("\n"); try self.flush(); } {#end_syntax_block#}{#syntax#}printValue{#endsyntax#} is a function that takes a parameter of any type, and does different things depending on the type:
{#code_begin|syntax|poc_printValue_fn#} const Writer = struct { pub fn printValue(self: *Writer, value: anytype) !void { switch (@typeInfo(@TypeOf(value))) { .Int => { return self.writeInt(value); }, .Float => { return self.writeFloat(value); }, .Pointer => { return self.write(value); }, else => { @compileError("Unable to print type '" ++ @typeName(@TypeOf(value)) ++ "'"); }, } } fn write(self: *Writer, value: []const u8) !void { _ = self; _ = value; } fn writeInt(self: *Writer, value: anytype) !void { _ = self; _ = value; } fn writeFloat(self: *Writer, value: anytype) !void { _ = self; _ = value; } }; {#code_end#}And now, what happens if we give too many arguments to {#syntax#}print{#endsyntax#}?
{#code_begin|test_err|unused argument in 'here is a string: '{s}' here is a number: {}#} const print = @import("std").debug.print; const a_number: i32 = 1234; const a_string = "foobar"; test "print too many arguments" { print("here is a string: '{s}' here is a number: {}\n", .{ a_string, a_number, a_number, }); } {#code_end#}Zig gives programmers the tools needed to protect themselves against their own mistakes.
Zig doesn't care whether the format argument is a string literal, only that it is a compile-time known value that can be coerced to a {#syntax#}[]const u8{#endsyntax#}:
{#code_begin|exe|print#} const print = @import("std").debug.print; const a_number: i32 = 1234; const a_string = "foobar"; const fmt = "here is a string: '{s}' here is a number: {}\n"; pub fn main() void { print(fmt, .{a_string, a_number}); } {#code_end#}This works fine.
Zig does not special case string formatting in the compiler and instead exposes enough power to accomplish this task in userland. It does so without introducing another language on top of Zig, such as a macro language or a preprocessor language. It's Zig all the way down.
{#header_close#} {#see_also|inline while|inline for#} {#header_close#} {#header_open|Assembly#}For some use cases, it may be necessary to directly control the machine code generated by Zig programs, rather than relying on Zig's code generation. For these cases, one can use inline assembly. Here is an example of implementing Hello, World on x86_64 Linux using inline assembly:
{#code_begin|exe#} {#target_linux_x86_64#} {#backend_stage1#} pub fn main() noreturn { const msg = "hello world\n"; _ = syscall3(SYS_write, STDOUT_FILENO, @ptrToInt(msg), msg.len); _ = syscall1(SYS_exit, 0); unreachable; } pub const SYS_write = 1; pub const SYS_exit = 60; pub const STDOUT_FILENO = 1; pub fn syscall1(number: usize, arg1: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) : [number] "{rax}" (number), [arg1] "{rdi}" (arg1) : "rcx", "r11" ); } pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) : [number] "{rax}" (number), [arg1] "{rdi}" (arg1), [arg2] "{rsi}" (arg2), [arg3] "{rdx}" (arg3) : "rcx", "r11" ); } {#code_end#}Dissecting the syntax:
{#syntax_block|zig|Assembly Syntax Explained#}// Inline assembly is an expression which returns a value. // the `asm` keyword begins the expression. _ = asm // `volatile` is an optional modifier that tells Zig this // inline assembly expression has side-effects. Without // `volatile`, Zig is allowed to delete the inline assembly // code if the result is unused. volatile ( // Next is a comptime string which is the assembly code. // Inside this string one may use `%[ret]`, `%[number]`, // or `%[arg1]` where a register is expected, to specify // the register that Zig uses for the argument or return value, // if the register constraint strings are used. However in // the below code, this is not used. A literal `%` can be // obtained by escaping it with a double percent: `%%`. // Often multiline string syntax comes in handy here. \\syscall // Next is the output. It is possible in the future Zig will // support multiple outputs, depending on how // https://github.com/ziglang/zig/issues/215 is resolved. // It is allowed for there to be no outputs, in which case // this colon would be directly followed by the colon for the inputs. : // This specifies the name to be used in `%[ret]` syntax in // the above assembly string. This example does not use it, // but the syntax is mandatory. [ret] // Next is the output constraint string. This feature is still // considered unstable in Zig, and so LLVM/GCC documentation // must be used to understand the semantics. // http://releases.llvm.org/10.0.0/docs/LangRef.html#inline-asm-constraint-string // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html // In this example, the constraint string means "the result value of // this inline assembly instruction is whatever is in $rax". "={rax}" // Next is either a value binding, or `->` and then a type. The // type is the result type of the inline assembly expression. // If it is a value binding, then `%[ret]` syntax would be used // to refer to the register bound to the value. (-> usize) // Next is the list of inputs. // The constraint for these inputs means, "when the assembly code is // executed, $rax shall have the value of `number` and $rdi shall have // the value of `arg1`". Any number of input parameters is allowed, // including none. : [number] "{rax}" (number), [arg1] "{rdi}" (arg1) // Next is the list of clobbers. These declare a set of registers whose // values will not be preserved by the execution of this assembly code. // These do not include output or input registers. The special clobber // value of "memory" means that the assembly writes to arbitrary undeclared // memory locations - not only the memory pointed to by a declared indirect // output. In this example we list $rcx and $r11 because it is known the // kernel syscall does not preserve these registers. : "rcx", "r11" );{#end_syntax_block#}For x86 and x86_64 targets, the syntax is AT&T syntax, rather than the more popular Intel syntax. This is due to technical constraints; assembly parsing is provided by LLVM and its support for Intel syntax is buggy and not well tested.
Some day Zig may have its own assembler. This would allow it to integrate more seamlessly into the language, as well as be compatible with the popular NASM syntax. This documentation section will be updated before 1.0.0 is released, with a conclusive statement about the status of AT&T vs Intel/NASM syntax.
{#header_open|Output Constraints#}Output constraints are still considered to be unstable in Zig, and so LLVM documentation and GCC documentation must be used to understand the semantics.
Note that some breaking changes to output constraints are planned with issue #215.
{#header_close#} {#header_open|Input Constraints#}Input constraints are still considered to be unstable in Zig, and so LLVM documentation and GCC documentation must be used to understand the semantics.
Note that some breaking changes to input constraints are planned with issue #215.
{#header_close#} {#header_open|Clobbers#}Clobbers are the set of registers whose values will not be preserved by the execution of the assembly code. These do not include output or input registers. The special clobber value of {#syntax#}"memory"{#endsyntax#} means that the assembly causes writes to arbitrary undeclared memory locations - not only the memory pointed to by a declared indirect output.
Failure to declare the full set of clobbers for a given inline assembly expression is unchecked {#link|Undefined Behavior#}.
{#header_close#} {#header_open|Global Assembly#}When an assembly expression occurs in a {#link|container|Containers#} level {#link|comptime#} block, this is global assembly.
This kind of assembly has different rules than inline assembly. First, {#syntax#}volatile{#endsyntax#}
is not valid because all global assembly is unconditionally included.
Second, there are no inputs, outputs, or clobbers. All global assembly is concatenated
verbatim into one long string and assembled together. There are no template substitution rules regarding
%
as there are in inline assembly expressions.
TODO: @fence()
TODO: @atomic rmw
TODO: builtin atomic memory ordering enum
{#header_close#} {#header_open|Async Functions#}When a function is called, a frame is pushed to the stack, the function runs until it reaches a return statement, and then the frame is popped from the stack. The code following the callsite does not run until the function returns.
An async function is a function whose execution is split into an {#syntax#}async{#endsyntax#} initiation, followed by an {#syntax#}await{#endsyntax#} completion. Its frame is provided explicitly by the caller, and it can be suspended and resumed any number of times.
The code following the {#syntax#}async{#endsyntax#} callsite runs immediately after the async function first suspends. When the return value of the async function is needed, the calling code can {#syntax#}await{#endsyntax#} on the async function frame. This will suspend the calling code until the async function completes, at which point execution resumes just after the {#syntax#}await{#endsyntax#} callsite.
Zig infers that a function is {#syntax#}async{#endsyntax#} when it observes that the function contains a suspension point. Async functions can be called the same as normal functions. A function call of an async function is a suspend point.
{#header_open|Suspend and Resume#}At any point, a function may suspend itself. This causes control flow to return to the callsite (in the case of the first suspension), or resumer (in the case of subsequent suspensions).
{#code_begin|test|suspend_no_resume#} {#backend_stage1#} const std = @import("std"); const expect = std.testing.expect; var x: i32 = 1; test "suspend with no resume" { var frame = async func(); try expect(x == 2); _ = frame; } fn func() void { x += 1; suspend {} // This line is never reached because the suspend has no matching resume. x += 1; } {#code_end#}In the same way that each allocation should have a corresponding free, Each {#syntax#}suspend{#endsyntax#} should have a corresponding {#syntax#}resume{#endsyntax#}. A suspend block allows a function to put a pointer to its own frame somewhere, for example into an event loop, even if that action will perform a {#syntax#}resume{#endsyntax#} operation on a different thread. {#link|@frame#} provides access to the async function frame pointer.
{#code_begin|test|async_suspend_block#} {#backend_stage1#} const std = @import("std"); const expect = std.testing.expect; var the_frame: anyframe = undefined; var result = false; test "async function suspend with block" { _ = async testSuspendBlock(); try expect(!result); resume the_frame; try expect(result); } fn testSuspendBlock() void { suspend { comptime try expect(@TypeOf(@frame()) == *@Frame(testSuspendBlock)); the_frame = @frame(); } result = true; } {#code_end#}{#syntax#}suspend{#endsyntax#} causes a function to be {#syntax#}async{#endsyntax#}.
{#header_open|Resuming from Suspend Blocks#}Upon entering a {#syntax#}suspend{#endsyntax#} block, the async function is already considered suspended, and can be resumed. For example, if you started another kernel thread, and had that thread call {#syntax#}resume{#endsyntax#} on the frame pointer provided by the {#link|@frame#}, the new thread would begin executing after the suspend block, while the old thread continued executing the suspend block.
However, the async function can be directly resumed from the suspend block, in which case it never returns to its resumer and continues executing.
{#code_begin|test|resume_from_suspend#} {#backend_stage1#} const std = @import("std"); const expect = std.testing.expect; test "resume from suspend" { var my_result: i32 = 1; _ = async testResumeFromSuspend(&my_result); try std.testing.expect(my_result == 2); } fn testResumeFromSuspend(my_result: *i32) void { suspend { resume @frame(); } my_result.* += 1; suspend {} my_result.* += 1; } {#code_end#}This is guaranteed to tail call, and therefore will not cause a new stack frame.
{#header_close#} {#header_close#} {#header_open|Async and Await#}In the same way that every {#syntax#}suspend{#endsyntax#} has a matching {#syntax#}resume{#endsyntax#}, every {#syntax#}async{#endsyntax#} has a matching {#syntax#}await{#endsyntax#} in standard code.
However, it is possible to have an {#syntax#}async{#endsyntax#} call without a matching {#syntax#}await{#endsyntax#}. Upon completion of the async function, execution would continue at the most recent {#syntax#}async{#endsyntax#} callsite or {#syntax#}resume{#endsyntax#} callsite, and the return value of the async function would be lost.
{#code_begin|test|async_await#} {#backend_stage1#} const std = @import("std"); const expect = std.testing.expect; test "async and await" { // The test block is not async and so cannot have a suspend // point in it. By using the nosuspend keyword, we promise that // the code in amain will finish executing without suspending // back to the test block. nosuspend amain(); } fn amain() void { var frame = async func(); comptime try expect(@TypeOf(frame) == @Frame(func)); const ptr: anyframe->void = &frame; const any_ptr: anyframe = ptr; resume any_ptr; await ptr; } fn func() void { suspend {} } {#code_end#}The {#syntax#}await{#endsyntax#} keyword is used to coordinate with an async function's {#syntax#}return{#endsyntax#} statement.
{#syntax#}await{#endsyntax#} is a suspend point, and takes as an operand anything that coerces to {#syntax#}anyframe->T{#endsyntax#}. Calling {#syntax#}await{#endsyntax#} on the frame of an async function will cause execution to continue at the {#syntax#}await{#endsyntax#} callsite once the target function completes.
There is a common misconception that {#syntax#}await{#endsyntax#} resumes the target function. It is the other way around: it suspends until the target function completes. In the event that the target function has already completed, {#syntax#}await{#endsyntax#} does not suspend; instead it copies the return value directly from the target function's frame.
{#code_begin|test|async_await_sequence#} {#backend_stage1#} const std = @import("std"); const expect = std.testing.expect; var the_frame: anyframe = undefined; var final_result: i32 = 0; test "async function await" { seq('a'); _ = async amain(); seq('f'); resume the_frame; seq('i'); try expect(final_result == 1234); try expect(std.mem.eql(u8, &seq_points, "abcdefghi")); } fn amain() void { seq('b'); var f = async another(); seq('e'); final_result = await f; seq('h'); } fn another() i32 { seq('c'); suspend { seq('d'); the_frame = @frame(); } seq('g'); return 1234; } var seq_points = [_]u8{0} ** "abcdefghi".len; var seq_index: usize = 0; fn seq(c: u8) void { seq_points[seq_index] = c; seq_index += 1; } {#code_end#}In general, {#syntax#}suspend{#endsyntax#} is lower level than {#syntax#}await{#endsyntax#}. Most application code will use only {#syntax#}async{#endsyntax#} and {#syntax#}await{#endsyntax#}, but event loop implementations will make use of {#syntax#}suspend{#endsyntax#} internally.
{#header_close#} {#header_open|Async Function Example#}Putting all of this together, here is an example of typical {#syntax#}async{#endsyntax#}/{#syntax#}await{#endsyntax#} usage:
{#code_begin|exe|async#} {#backend_stage1#} const std = @import("std"); const Allocator = std.mem.Allocator; pub fn main() void { _ = async amainWrap(); // Typically we would use an event loop to manage resuming async functions, // but in this example we hard code what the event loop would do, // to make things deterministic. resume global_file_frame; resume global_download_frame; } fn amainWrap() void { amain() catch |e| { std.debug.print("{}\n", .{e}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } std.process.exit(1); }; } fn amain() !void { const allocator = std.heap.page_allocator; var download_frame = async fetchUrl(allocator, "https://example.com/"); var awaited_download_frame = false; errdefer if (!awaited_download_frame) { if (await download_frame) |r| allocator.free(r) else |_| {} }; var file_frame = async readFile(allocator, "something.txt"); var awaited_file_frame = false; errdefer if (!awaited_file_frame) { if (await file_frame) |r| allocator.free(r) else |_| {} }; awaited_file_frame = true; const file_text = try await file_frame; defer allocator.free(file_text); awaited_download_frame = true; const download_text = try await download_frame; defer allocator.free(download_text); std.debug.print("download_text: {s}\n", .{download_text}); std.debug.print("file_text: {s}\n", .{file_text}); } var global_download_frame: anyframe = undefined; fn fetchUrl(allocator: Allocator, url: []const u8) ![]u8 { _ = url; // this is just an example, we don't actually do it! const result = try allocator.dupe(u8, "this is the downloaded url contents"); errdefer allocator.free(result); suspend { global_download_frame = @frame(); } std.debug.print("fetchUrl returning\n", .{}); return result; } var global_file_frame: anyframe = undefined; fn readFile(allocator: Allocator, filename: []const u8) ![]u8 { _ = filename; // this is just an example, we don't actually do it! const result = try allocator.dupe(u8, "this is the file contents"); errdefer allocator.free(result); suspend { global_file_frame = @frame(); } std.debug.print("readFile returning\n", .{}); return result; } {#code_end#}Now we remove the {#syntax#}suspend{#endsyntax#} and {#syntax#}resume{#endsyntax#} code, and observe the same behavior, with one tiny difference:
{#code_begin|exe|blocking#} {#backend_stage1#} const std = @import("std"); const Allocator = std.mem.Allocator; pub fn main() void { _ = async amainWrap(); } fn amainWrap() void { amain() catch |e| { std.debug.print("{}\n", .{e}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } std.process.exit(1); }; } fn amain() !void { const allocator = std.heap.page_allocator; var download_frame = async fetchUrl(allocator, "https://example.com/"); var awaited_download_frame = false; errdefer if (!awaited_download_frame) { if (await download_frame) |r| allocator.free(r) else |_| {} }; var file_frame = async readFile(allocator, "something.txt"); var awaited_file_frame = false; errdefer if (!awaited_file_frame) { if (await file_frame) |r| allocator.free(r) else |_| {} }; awaited_file_frame = true; const file_text = try await file_frame; defer allocator.free(file_text); awaited_download_frame = true; const download_text = try await download_frame; defer allocator.free(download_text); std.debug.print("download_text: {s}\n", .{download_text}); std.debug.print("file_text: {s}\n", .{file_text}); } fn fetchUrl(allocator: Allocator, url: []const u8) ![]u8 { _ = url; // this is just an example, we don't actually do it! const result = try allocator.dupe(u8, "this is the downloaded url contents"); errdefer allocator.free(result); std.debug.print("fetchUrl returning\n", .{}); return result; } fn readFile(allocator: Allocator, filename: []const u8) ![]u8 { _ = filename; // this is just an example, we don't actually do it! const result = try allocator.dupe(u8, "this is the file contents"); errdefer allocator.free(result); std.debug.print("readFile returning\n", .{}); return result; } {#code_end#}Previously, the {#syntax#}fetchUrl{#endsyntax#} and {#syntax#}readFile{#endsyntax#} functions suspended, and were resumed in an order determined by the {#syntax#}main{#endsyntax#} function. Now, since there are no suspend points, the order of the printed "... returning" messages is determined by the order of {#syntax#}async{#endsyntax#} callsites.
{#header_close#} {#header_close#} {#header_open|Builtin Functions|2col#}
Builtin functions are provided by the compiler and are prefixed with @
.
The {#syntax#}comptime{#endsyntax#} keyword on a parameter means that the parameter must be known
at compile time.
{#syntax#}@addrSpaceCast(comptime addrspace: std.builtin.AddressSpace, ptr: anytype) anytype{#endsyntax#}
Converts a pointer from one address space to another. Depending on the current target and address spaces, this cast may be a no-op, a complex operation, or illegal. If the cast is legal, then the resulting pointer points to the same memory location as the pointer operand. It is always valid to cast a pointer between the same address spaces.
{#header_close#} {#header_open|@addWithOverflow#}{#syntax#}@addWithOverflow(comptime T: type, a: T, b: T, result: *T) bool{#endsyntax#}
Performs {#syntax#}result.* = a + b{#endsyntax#}. If overflow or underflow occurs, stores the overflowed bits in {#syntax#}result{#endsyntax#} and returns {#syntax#}true{#endsyntax#}. If no overflow or underflow occurs, returns {#syntax#}false{#endsyntax#}.
{#header_close#} {#header_open|@alignCast#}{#syntax#}@alignCast(comptime alignment: u29, ptr: anytype) anytype{#endsyntax#}
{#syntax#}ptr{#endsyntax#} can be {#syntax#}*T{#endsyntax#}, {#syntax#}?*T{#endsyntax#}, or {#syntax#}[]T{#endsyntax#}. It returns the same type as {#syntax#}ptr{#endsyntax#} except with the alignment adjusted to the new value.
A {#link|pointer alignment safety check|Incorrect Pointer Alignment#} is added to the generated code to make sure the pointer is aligned as promised.
{#header_close#} {#header_open|@alignOf#}{#syntax#}@alignOf(comptime T: type) comptime_int{#endsyntax#}
This function returns the number of bytes that this type should be aligned to for the current target to match the C ABI. When the child type of a pointer has this alignment, the alignment can be omitted from the type.
{#syntax#}const assert = @import("std").debug.assert; comptime { assert(*u32 == *align(@alignOf(u32)) u32); }{#endsyntax#}
The result is a target-specific compile time constant. It is guaranteed to be less than or equal to {#link|@sizeOf(T)|@sizeOf#}.
{#see_also|Alignment#} {#header_close#} {#header_open|@as#}{#syntax#}@as(comptime T: type, expression) T{#endsyntax#}
Performs {#link|Type Coercion#}. This cast is allowed when the conversion is unambiguous and safe, and is the preferred way to convert between types, whenever possible.
{#header_close#} {#header_open|@asyncCall#}{#syntax#}@asyncCall(frame_buffer: []align(@alignOf(@Frame(anyAsyncFunction))) u8, result_ptr, function_ptr, args: anytype) anyframe->T{#endsyntax#}
{#syntax#}@asyncCall{#endsyntax#} performs an {#syntax#}async{#endsyntax#} call on a function pointer, which may or may not be an {#link|async function|Async Functions#}.
The provided {#syntax#}frame_buffer{#endsyntax#} must be large enough to fit the entire function frame. This size can be determined with {#link|@frameSize#}. To provide a too-small buffer invokes safety-checked {#link|Undefined Behavior#}.
{#syntax#}result_ptr{#endsyntax#} is optional ({#link|null#} may be provided). If provided, the function call will write its result directly to the result pointer, which will be available to read after {#link|await|Async and Await#} completes. Any result location provided to {#syntax#}await{#endsyntax#} will copy the result from {#syntax#}result_ptr{#endsyntax#}.
{#code_begin|test|async_struct_field_fn_pointer#} {#backend_stage1#} const std = @import("std"); const expect = std.testing.expect; test "async fn pointer in a struct field" { var data: i32 = 1; const Foo = struct { bar: fn (*i32) callconv(.Async) void, }; var foo = Foo{ .bar = func }; var bytes: [64]u8 align(@alignOf(@Frame(func))) = undefined; const f = @asyncCall(&bytes, {}, foo.bar, .{&data}); try expect(data == 2); resume f; try expect(data == 4); } fn func(y: *i32) void { defer y.* += 2; y.* += 1; suspend {} } {#code_end#} {#header_close#} {#header_open|@atomicLoad#}{#syntax#}@atomicLoad(comptime T: type, ptr: *const T, comptime ordering: builtin.AtomicOrder) T{#endsyntax#}
This builtin function atomically dereferences a pointer and returns the value.
{#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float, an integer or an enum.
{#see_also|@atomicStore|@atomicRmw|@fence|@cmpxchgWeak|@cmpxchgStrong#} {#header_close#} {#header_open|@atomicRmw#}{#syntax#}@atomicRmw(comptime T: type, ptr: *T, comptime op: builtin.AtomicRmwOp, operand: T, comptime ordering: builtin.AtomicOrder) T{#endsyntax#}
This builtin function atomically modifies memory and then returns the previous value.
{#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float, an integer or an enum.
Supported operations:
- {#syntax#}.Xchg{#endsyntax#} - stores the operand unmodified. Supports enums, integers and floats.
- {#syntax#}.Add{#endsyntax#} - for integers, twos complement wraparound addition. Also supports {#link|Floats#}.
- {#syntax#}.Sub{#endsyntax#} - for integers, twos complement wraparound subtraction. Also supports {#link|Floats#}.
- {#syntax#}.And{#endsyntax#} - bitwise and
- {#syntax#}.Nand{#endsyntax#} - bitwise nand
- {#syntax#}.Or{#endsyntax#} - bitwise or
- {#syntax#}.Xor{#endsyntax#} - bitwise xor
- {#syntax#}.Max{#endsyntax#} - stores the operand if it is larger. Supports integers and floats.
- {#syntax#}.Min{#endsyntax#} - stores the operand if it is smaller. Supports integers and floats.
{#syntax#}@atomicStore(comptime T: type, ptr: *T, value: T, comptime ordering: builtin.AtomicOrder) void{#endsyntax#}
This builtin function atomically stores a value.
{#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float, an integer or an enum.
{#see_also|@atomicLoad|@atomicRmw|@fence|@cmpxchgWeak|@cmpxchgStrong#} {#header_close#} {#header_open|@bitCast#}{#syntax#}@bitCast(comptime DestType: type, value: anytype) DestType{#endsyntax#}
Converts a value of one type to another type.
Asserts that {#syntax#}@sizeOf(@TypeOf(value)) == @sizeOf(DestType){#endsyntax#}.
Asserts that {#syntax#}@typeInfo(DestType) != .Pointer{#endsyntax#}. Use {#syntax#}@ptrCast{#endsyntax#} or {#syntax#}@intToPtr{#endsyntax#} if you need this.
Can be used for these things for example:
- Convert {#syntax#}f32{#endsyntax#} to {#syntax#}u32{#endsyntax#} bits
- Convert {#syntax#}i32{#endsyntax#} to {#syntax#}u32{#endsyntax#} preserving twos complement
Works at compile-time if {#syntax#}value{#endsyntax#} is known at compile time. It's a compile error to bitcast a value of undefined layout; this means that, besides the restriction from types which possess dedicated casting builtins (enums, pointers, error sets), bare structs, error unions, slices, optionals, and any other type without a well-defined memory layout, also cannot be used in this operation.
{#header_close#} {#header_open|@bitOffsetOf#}{#syntax#}@bitOffsetOf(comptime T: type, comptime field_name: []const u8) comptime_int{#endsyntax#}
Returns the bit offset of a field relative to its containing struct.
For non {#link|packed structs|packed struct#}, this will always be divisible by {#syntax#}8{#endsyntax#}. For packed structs, non-byte-aligned fields will share a byte offset, but they will have different bit offsets.
{#see_also|@offsetOf#} {#header_close#} {#header_open|@boolToInt#}{#syntax#}@boolToInt(value: bool) u1{#endsyntax#}
Converts {#syntax#}true{#endsyntax#} to {#syntax#}@as(u1, 1){#endsyntax#} and {#syntax#}false{#endsyntax#} to {#syntax#}@as(u1, 0){#endsyntax#}.
If the value is known at compile-time, the return type is {#syntax#}comptime_int{#endsyntax#} instead of {#syntax#}u1{#endsyntax#}.
{#header_close#} {#header_open|@bitSizeOf#}{#syntax#}@bitSizeOf(comptime T: type) comptime_int{#endsyntax#}
This function returns the number of bits it takes to store {#syntax#}T{#endsyntax#} in memory if the type were a field in a packed struct/union. The result is a target-specific compile time constant.
This function measures the size at runtime. For types that are disallowed at runtime, such as {#syntax#}comptime_int{#endsyntax#} and {#syntax#}type{#endsyntax#}, the result is {#syntax#}0{#endsyntax#}.
{#see_also|@sizeOf|@typeInfo#} {#header_close#} {#header_open|@breakpoint#}{#syntax#}@breakpoint(){#endsyntax#}
This function inserts a platform-specific debug trap instruction which causes debuggers to break there.
This function is only valid within function scope.
{#header_close#} {#header_open|@mulAdd#}{#syntax#}@mulAdd(comptime T: type, a: T, b: T, c: T) T{#endsyntax#}
Fused multiply-add, similar to {#syntax#}(a * b) + c{#endsyntax#}, except only rounds once, and is thus more accurate.
Supports {#link|Floats#} and {#link|Vectors#} of floats.
{#header_close#} {#header_open|@byteSwap#}{#syntax#}@byteSwap(operand: anytype) T{#endsyntax#}
{#syntax#}@TypeOf(operand){#endsyntax#} must be an integer type or an integer vector type with bit count evenly divisible by 8.
{#syntax#}operand{#endsyntax#} may be an {#link|integer|Integers#} or {#link|vector|Vectors#}.
Swaps the byte order of the integer. This converts a big endian integer to a little endian integer, and converts a little endian integer to a big endian integer.
Note that for the purposes of memory layout with respect to endianness, the integer type should be related to the number of bytes reported by {#link|@sizeOf#} bytes. This is demonstrated with {#syntax#}u24{#endsyntax#}. {#syntax#}@sizeOf(u24) == 4{#endsyntax#}, which means that a {#syntax#}u24{#endsyntax#} stored in memory takes 4 bytes, and those 4 bytes are what are swapped on a little vs big endian system. On the other hand, if {#syntax#}T{#endsyntax#} is specified to be {#syntax#}u24{#endsyntax#}, then only 3 bytes are reversed.
{#header_close#} {#header_open|@bitReverse#}{#syntax#}@bitReverse(integer: anytype) T{#endsyntax#}
{#syntax#}@TypeOf(anytype){#endsyntax#} accepts any integer type or integer vector type.
Reverses the bitpattern of an integer value, including the sign bit if applicable.
For example 0b10110110 ({#syntax#}u8 = 182{#endsyntax#}, {#syntax#}i8 = -74{#endsyntax#}) becomes 0b01101101 ({#syntax#}u8 = 109{#endsyntax#}, {#syntax#}i8 = 109{#endsyntax#}).
{#header_close#} {#header_open|@offsetOf#}{#syntax#}@offsetOf(comptime T: type, comptime field_name: []const u8) comptime_int{#endsyntax#}
Returns the byte offset of a field relative to its containing struct.
{#see_also|@bitOffsetOf#} {#header_close#} {#header_open|@call#}{#syntax#}@call(options: std.builtin.CallOptions, function: anytype, args: anytype) anytype{#endsyntax#}
Calls a function, in the same way that invoking an expression with parentheses does:
{#code_begin|test|call#} const expect = @import("std").testing.expect; test "noinline function call" { try expect(@call(.{}, add, .{3, 9}) == 12); } fn add(a: i32, b: i32) i32 { return a + b; } {#code_end#}{#syntax#}@call{#endsyntax#} allows more flexibility than normal function call syntax does. The {#syntax#}CallOptions{#endsyntax#} struct is reproduced here:
{#syntax_block|zig|builtin.CallOptions struct#} pub const CallOptions = struct { modifier: Modifier = .auto, /// Only valid when `Modifier` is `Modifier.async_kw`. stack: ?[]align(std.Target.stack_align) u8 = null, pub const Modifier = enum { /// Equivalent to function call syntax. auto, /// Equivalent to async keyword used with function call syntax. async_kw, /// Prevents tail call optimization. This guarantees that the return /// address will point to the callsite, as opposed to the callsite's /// callsite. If the call is otherwise required to be tail-called /// or inlined, a compile error is emitted instead. never_tail, /// Guarantees that the call will not be inlined. If the call is /// otherwise required to be inlined, a compile error is emitted instead. never_inline, /// Asserts that the function call will not suspend. This allows a /// non-async function to call an async function. no_async, /// Guarantees that the call will be generated with tail call optimization. /// If this is not possible, a compile error is emitted instead. always_tail, /// Guarantees that the call will inlined at the callsite. /// If this is not possible, a compile error is emitted instead. always_inline, /// Evaluates the call at compile-time. If the call cannot be completed at /// compile-time, a compile error is emitted instead. compile_time, }; }; {#end_syntax_block#} {#header_close#} {#header_open|@cDefine#}{#syntax#}@cDefine(comptime name: []u8, value){#endsyntax#}
This function can only occur inside {#syntax#}@cImport{#endsyntax#}.
This appends #define $name $value
to the {#syntax#}@cImport{#endsyntax#}
temporary buffer.
To define without a value, like this:
#define _GNU_SOURCE
Use the void value, like this:
{#syntax#}@cDefine("_GNU_SOURCE", {}){#endsyntax#}{#see_also|Import from C Header File|@cInclude|@cImport|@cUndef|void#} {#header_close#} {#header_open|@cImport#}
{#syntax#}@cImport(expression) type{#endsyntax#}
This function parses C code and imports the functions, types, variables, and compatible macro definitions into a new empty struct type, and then returns that type.
{#syntax#}expression{#endsyntax#} is interpreted at compile time. The builtin functions {#syntax#}@cInclude{#endsyntax#}, {#syntax#}@cDefine{#endsyntax#}, and {#syntax#}@cUndef{#endsyntax#} work within this expression, appending to a temporary buffer which is then parsed as C code.
Usually you should only have one {#syntax#}@cImport{#endsyntax#} in your entire application, because it saves the compiler from invoking clang multiple times, and prevents inline functions from being duplicated.
Reasons for having multiple {#syntax#}@cImport{#endsyntax#} expressions would be:
- To avoid a symbol collision, for example if foo.h and bar.h both
#define CONNECTION_COUNT
- To analyze the C code with different preprocessor defines
{#syntax#}@cInclude(comptime path: []u8){#endsyntax#}
This function can only occur inside {#syntax#}@cImport{#endsyntax#}.
This appends #include <$path>\n
to the {#syntax#}c_import{#endsyntax#}
temporary buffer.
{#syntax#}@clz(operand: anytype){#endsyntax#}
{#syntax#}@TypeOf(operand){#endsyntax#} must be an integer type or an integer vector type.
{#syntax#}operand{#endsyntax#} may be an {#link|integer|Integers#} or {#link|vector|Vectors#}.
This function counts the number of most-significant (leading in a big-Endian sense) zeroes in an integer.
If {#syntax#}operand{#endsyntax#} is a {#link|comptime#}-known integer, the return type is {#syntax#}comptime_int{#endsyntax#}. Otherwise, the return type is an unsigned integer or vector of unsigned integers with the minimum number of bits that can represent the bit count of the integer type.
If {#syntax#}operand{#endsyntax#} is zero, {#syntax#}@clz{#endsyntax#} returns the bit width of integer type {#syntax#}T{#endsyntax#}.
{#see_also|@ctz|@popCount#} {#header_close#} {#header_open|@cmpxchgStrong#}{#syntax#}@cmpxchgStrong(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T{#endsyntax#}
This function performs a strong atomic compare exchange operation. It's the equivalent of this code, except atomic:
{#code_begin|syntax#} fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T { const old_value = ptr.*; if (old_value == expected_value) { ptr.* = new_value; return null; } else { return old_value; } } {#code_end#}If you are using cmpxchg in a loop, {#link|@cmpxchgWeak#} is the better choice, because it can be implemented more efficiently in machine instructions.
{#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float, an integer or an enum.
{#syntax#}@typeInfo(@TypeOf(ptr)).Pointer.alignment{#endsyntax#} must be {#syntax#}>= @sizeOf(T).{#endsyntax#}
{#see_also|@atomicStore|@atomicLoad|@atomicRmw|@fence|@cmpxchgWeak#} {#header_close#} {#header_open|@cmpxchgWeak#}{#syntax#}@cmpxchgWeak(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T{#endsyntax#}
This function performs a weak atomic compare exchange operation. It's the equivalent of this code, except atomic:
{#syntax_block|zig|cmpxchgWeakButNotAtomic#} fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T { const old_value = ptr.*; if (old_value == expected_value and usuallyTrueButSometimesFalse()) { ptr.* = new_value; return null; } else { return old_value; } } {#end_syntax_block#}If you are using cmpxchg in a loop, the sporadic failure will be no problem, and {#syntax#}cmpxchgWeak{#endsyntax#} is the better choice, because it can be implemented more efficiently in machine instructions. However if you need a stronger guarantee, use {#link|@cmpxchgStrong#}.
{#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float, an integer or an enum.
{#syntax#}@typeInfo(@TypeOf(ptr)).Pointer.alignment{#endsyntax#} must be {#syntax#}>= @sizeOf(T).{#endsyntax#}
{#see_also|@atomicStore|@atomicLoad|@atomicRmw|@fence|@cmpxchgStrong#} {#header_close#} {#header_open|@compileError#}{#syntax#}@compileError(comptime msg: []u8){#endsyntax#}
This function, when semantically analyzed, causes a compile error with the message {#syntax#}msg{#endsyntax#}.
There are several ways that code avoids being semantically checked, such as using {#syntax#}if{#endsyntax#} or {#syntax#}switch{#endsyntax#} with compile time constants, and {#syntax#}comptime{#endsyntax#} functions.
{#header_close#} {#header_open|@compileLog#}{#syntax#}@compileLog(args: ...){#endsyntax#}
This function prints the arguments passed to it at compile-time.
To prevent accidentally leaving compile log statements in a codebase, a compilation error is added to the build, pointing to the compile log statement. This error prevents code from being generated, but does not otherwise interfere with analysis.
This function can be used to do "printf debugging" on compile-time executing code.
{#code_begin|test_err|found compile log statement#} const print = @import("std").debug.print; const num1 = blk: { var val1: i32 = 99; @compileLog("comptime val1 = ", val1); val1 = val1 + 1; break :blk val1; }; test "main" { @compileLog("comptime in main"); print("Runtime in main, num1 = {}.\n", .{num1}); } {#code_end#}If all {#syntax#}@compileLog{#endsyntax#} calls are removed or not encountered by analysis, the program compiles successfully and the generated executable prints:
{#code_begin|test|without_compileLog#} const print = @import("std").debug.print; const num1 = blk: { var val1: i32 = 99; val1 = val1 + 1; break :blk val1; }; test "main" { print("Runtime in main, num1 = {}.\n", .{num1}); } {#code_end#} {#header_close#} {#header_open|@ctz#}{#syntax#}@ctz(operand: anytype){#endsyntax#}
{#syntax#}@TypeOf(operand){#endsyntax#} must be an integer type or an integer vector type.
{#syntax#}operand{#endsyntax#} may be an {#link|integer|Integers#} or {#link|vector|Vectors#}.
This function counts the number of least-significant (trailing in a big-Endian sense) zeroes in an integer.
If {#syntax#}operand{#endsyntax#} is a {#link|comptime#}-known integer, the return type is {#syntax#}comptime_int{#endsyntax#}. Otherwise, the return type is an unsigned integer or vector of unsigned integers with the minimum number of bits that can represent the bit count of the integer type.
If {#syntax#}operand{#endsyntax#} is zero, {#syntax#}@ctz{#endsyntax#} returns the bit width of integer type {#syntax#}T{#endsyntax#}.
{#see_also|@clz|@popCount#} {#header_close#} {#header_open|@cUndef#}{#syntax#}@cUndef(comptime name: []u8){#endsyntax#}
This function can only occur inside {#syntax#}@cImport{#endsyntax#}.
This appends #undef $name
to the {#syntax#}@cImport{#endsyntax#}
temporary buffer.
{#syntax#}@divExact(numerator: T, denominator: T) T{#endsyntax#}
Exact division. Caller guarantees {#syntax#}denominator != 0{#endsyntax#} and {#syntax#}@divTrunc(numerator, denominator) * denominator == numerator{#endsyntax#}.
- {#syntax#}@divExact(6, 3) == 2{#endsyntax#}
- {#syntax#}@divExact(a, b) * b == a{#endsyntax#}
For a function that returns a possible error code, use {#syntax#}@import("std").math.divExact{#endsyntax#}.
{#see_also|@divTrunc|@divFloor#} {#header_close#} {#header_open|@divFloor#}{#syntax#}@divFloor(numerator: T, denominator: T) T{#endsyntax#}
Floored division. Rounds toward negative infinity. For unsigned integers it is the same as {#syntax#}numerator / denominator{#endsyntax#}. Caller guarantees {#syntax#}denominator != 0{#endsyntax#} and {#syntax#}!(@typeInfo(T) == .Int and T.is_signed and numerator == std.math.minInt(T) and denominator == -1){#endsyntax#}.
- {#syntax#}@divFloor(-5, 3) == -2{#endsyntax#}
- {#syntax#}(@divFloor(a, b) * b) + @mod(a, b) == a{#endsyntax#}
For a function that returns a possible error code, use {#syntax#}@import("std").math.divFloor{#endsyntax#}.
{#see_also|@divTrunc|@divExact#} {#header_close#} {#header_open|@divTrunc#}{#syntax#}@divTrunc(numerator: T, denominator: T) T{#endsyntax#}
Truncated division. Rounds toward zero. For unsigned integers it is the same as {#syntax#}numerator / denominator{#endsyntax#}. Caller guarantees {#syntax#}denominator != 0{#endsyntax#} and {#syntax#}!(@typeInfo(T) == .Int and T.is_signed and numerator == std.math.minInt(T) and denominator == -1){#endsyntax#}.
- {#syntax#}@divTrunc(-5, 3) == -1{#endsyntax#}
- {#syntax#}(@divTrunc(a, b) * b) + @rem(a, b) == a{#endsyntax#}
For a function that returns a possible error code, use {#syntax#}@import("std").math.divTrunc{#endsyntax#}.
{#see_also|@divFloor|@divExact#} {#header_close#} {#header_open|@embedFile#}{#syntax#}@embedFile(comptime path: []const u8) *const [N:0]u8{#endsyntax#}
This function returns a compile time constant pointer to null-terminated, fixed-size array with length equal to the byte count of the file given by {#syntax#}path{#endsyntax#}. The contents of the array are the contents of the file. This is equivalent to a {#link|string literal|String Literals and Unicode Code Point Literals#} with the file contents.
{#syntax#}path{#endsyntax#} is absolute or relative to the current file, just like {#syntax#}@import{#endsyntax#}.
{#see_also|@import#} {#header_close#} {#header_open|@enumToInt#}{#syntax#}@enumToInt(enum_or_tagged_union: anytype) anytype{#endsyntax#}
Converts an enumeration value into its integer tag type. When a tagged union is passed, the tag value is used as the enumeration value.
If there is only one possible enum value, the result is a {#syntax#}comptime_int{#endsyntax#} known at {#link|comptime#}.
{#see_also|@intToEnum#} {#header_close#} {#header_open|@errorName#}{#syntax#}@errorName(err: anyerror) [:0]const u8{#endsyntax#}
This function returns the string representation of an error. The string representation of {#syntax#}error.OutOfMem{#endsyntax#} is {#syntax#}"OutOfMem"{#endsyntax#}.
If there are no calls to {#syntax#}@errorName{#endsyntax#} in an entire application, or all calls have a compile-time known value for {#syntax#}err{#endsyntax#}, then no error name table will be generated.
{#header_close#} {#header_open|@errorReturnTrace#}{#syntax#}@errorReturnTrace() ?*builtin.StackTrace{#endsyntax#}
If the binary is built with error return tracing, and this function is invoked in a function that calls a function with an error or error union return type, returns a stack trace object. Otherwise returns {#link|null#}.
{#header_close#} {#header_open|@errorToInt#}{#syntax#}@errorToInt(err: anytype) std.meta.Int(.unsigned, @sizeOf(anyerror) * 8){#endsyntax#}
Supports the following types:
- {#link|The Global Error Set#}
- {#link|Error Set Type#}
- {#link|Error Union Type#}
Converts an error to the integer representation of an error.
It is generally recommended to avoid this cast, as the integer representation of an error is not stable across source code changes.
{#see_also|@intToError#} {#header_close#} {#header_open|@errSetCast#}{#syntax#}@errSetCast(comptime T: DestType, value: anytype) DestType{#endsyntax#}
Converts an error value from one error set to another error set. Attempting to convert an error which is not in the destination error set results in safety-protected {#link|Undefined Behavior#}.
{#header_close#} {#header_open|@export#}{#syntax#}@export(declaration, comptime options: std.builtin.ExportOptions) void{#endsyntax#}
Creates a symbol in the output object file.
declaration
must be one of two things:
- An identifier ({#syntax#}x{#endsyntax#}) identifying a {#link|function|Functions#} or a {#link|variable|Container Level Variables#}.
- Field access ({#syntax#}x.y{#endsyntax#}) looking up a {#link|function|Functions#} or a {#link|variable|Container Level Variables#}.
This builtin can be called from a {#link|comptime#} block to conditionally export symbols.
When declaration
is a function with the C calling convention and
{#syntax#}options.linkage{#endsyntax#} is {#syntax#}Strong{#endsyntax#}, this is equivalent to
the {#syntax#}export{#endsyntax#} keyword used on a function:
This is equivalent to:
{#code_begin|obj#} export fn foo() void {} {#code_end#}Note that even when using {#syntax#}export{#endsyntax#}, the {#syntax#}@"foo"{#endsyntax#} syntax for {#link|identifiers|Identifiers#} can be used to choose any string for the symbol name:
{#code_begin|obj#} export fn @"A function name that is a complete sentence."() void {} {#code_end#}When looking at the resulting object, you can see the symbol is used verbatim:
00000000000001f0 T A function name that is a complete sentence.
{#see_also|Exporting a C Library#}
{#header_close#}
{#header_open|@extern#}
{#syntax#}@extern(T: type, comptime options: std.builtin.ExternOptions) *T{#endsyntax#}
Creates a reference to an external symbol in the output object file.
{#see_also|@export#} {#header_close#} {#header_open|@fence#}{#syntax#}@fence(order: AtomicOrder){#endsyntax#}
The {#syntax#}fence{#endsyntax#} function is used to introduce happens-before edges between operations.
{#syntax#}AtomicOrder{#endsyntax#} can be found with {#syntax#}@import("std").builtin.AtomicOrder{#endsyntax#}.
{#see_also|@atomicStore|@atomicLoad|@atomicRmw|@cmpxchgWeak|@cmpxchgStrong#} {#header_close#} {#header_open|@field#}{#syntax#}@field(lhs: anytype, comptime field_name: []const u8) (field){#endsyntax#}
Performs field access by a compile-time string. Works on both fields and declarations.
{#code_begin|test|field_decl_access_by_string#} const std = @import("std"); const Point = struct { x: u32, y: u32, pub var z: u32 = 1; }; test "field access by string" { const expect = std.testing.expect; var p = Point{ .x = 0, .y = 0 }; @field(p, "x") = 4; @field(p, "y") = @field(p, "x") + 1; try expect(@field(p, "x") == 4); try expect(@field(p, "y") == 5); } test "decl access by string" { const expect = std.testing.expect; try expect(@field(Point, "z") == 1); @field(Point, "z") = 2; try expect(@field(Point, "z") == 2); } {#code_end#} {#header_close#} {#header_open|@fieldParentPtr#}{#syntax#}@fieldParentPtr(comptime ParentType: type, comptime field_name: []const u8, field_ptr: *T) *ParentType{#endsyntax#}
Given a pointer to a field, returns the base pointer of a struct.
{#header_close#} {#header_open|@floatCast#}{#syntax#}@floatCast(comptime DestType: type, value: anytype) DestType{#endsyntax#}
Convert from one float type to another. This cast is safe, but may cause the numeric value to lose precision.
{#header_close#} {#header_open|@floatToInt#}{#syntax#}@floatToInt(comptime DestType: type, float: anytype) DestType{#endsyntax#}
Converts the integer part of a floating point number to the destination type.
If the integer part of the floating point number cannot fit in the destination type, it invokes safety-checked {#link|Undefined Behavior#}.
{#see_also|@intToFloat#} {#header_close#} {#header_open|@frame#}{#syntax#}@frame() *@Frame(func){#endsyntax#}
This function returns a pointer to the frame for a given function. This type can be {#link|coerced|Type Coercion#} to {#syntax#}anyframe->T{#endsyntax#} and to {#syntax#}anyframe{#endsyntax#}, where {#syntax#}T{#endsyntax#} is the return type of the function in scope.
This function does not mark a suspension point, but it does cause the function in scope to become an {#link|async function|Async Functions#}.
{#header_close#} {#header_open|@Frame#}{#syntax#}@Frame(func: anytype) type{#endsyntax#}
This function returns the frame type of a function. This works for {#link|Async Functions#} as well as any function without a specific calling convention.
This type is suitable to be used as the return type of {#link|async|Async and Await#} which allows one to, for example, heap-allocate an async function frame:
{#code_begin|test|heap_allocated_frame#} {#backend_stage1#} const std = @import("std"); test "heap allocated frame" { const frame = try std.heap.page_allocator.create(@Frame(func)); frame.* = async func(); } fn func() void { suspend {} } {#code_end#} {#header_close#} {#header_open|@frameAddress#}{#syntax#}@frameAddress() usize{#endsyntax#}
This function returns the base pointer of the current stack frame.
The implications of this are target-specific and not consistent across all platforms. The frame address may not be available in release mode due to aggressive optimizations.
This function is only valid within function scope.
{#header_close#} {#header_open|@frameSize#}{#syntax#}@frameSize(func: anytype) usize{#endsyntax#}
This is the same as {#syntax#}@sizeOf(@Frame(func)){#endsyntax#}, where {#syntax#}func{#endsyntax#} may be runtime-known.
This function is typically used in conjunction with {#link|@asyncCall#}.
{#header_close#} {#header_open|@hasDecl#}{#syntax#}@hasDecl(comptime Container: type, comptime name: []const u8) bool{#endsyntax#}
Returns whether or not a {#link|container|Containers#} has a declaration matching {#syntax#}name{#endsyntax#}.
{#code_begin|test|hasDecl#} const std = @import("std"); const expect = std.testing.expect; const Foo = struct { nope: i32, pub var blah = "xxx"; const hi = 1; }; test "@hasDecl" { try expect(@hasDecl(Foo, "blah")); // Even though `hi` is private, @hasDecl returns true because this test is // in the same file scope as Foo. It would return false if Foo was declared // in a different file. try expect(@hasDecl(Foo, "hi")); // @hasDecl is for declarations; not fields. try expect(!@hasDecl(Foo, "nope")); try expect(!@hasDecl(Foo, "nope1234")); } {#code_end#} {#see_also|@hasField#} {#header_close#} {#header_open|@hasField#}{#syntax#}@hasField(comptime Container: type, comptime name: []const u8) bool{#endsyntax#}
Returns whether the field name of a struct, union, or enum exists.
The result is a compile time constant.
It does not include functions, variables, or constants.
{#see_also|@hasDecl#} {#header_close#} {#header_open|@import#}{#syntax#}@import(comptime path: []u8) type{#endsyntax#}
This function finds a zig file corresponding to {#syntax#}path{#endsyntax#} and adds it to the build, if it is not already added.
Zig source files are implicitly structs, with a name equal to the file's basename with the extension truncated. {#syntax#}@import{#endsyntax#} returns the struct type corresponding to the file.
Declarations which have the {#syntax#}pub{#endsyntax#} keyword may be referenced from a different source file than the one they are declared in.
{#syntax#}path{#endsyntax#} can be a relative path or it can be the name of a package. If it is a relative path, it is relative to the file that contains the {#syntax#}@import{#endsyntax#} function call.
The following packages are always available:
- {#syntax#}@import("std"){#endsyntax#} - Zig Standard Library
- {#syntax#}@import("builtin"){#endsyntax#} - Target-specific information.
The command
zig build-exe --show-builtin
outputs the source to stdout for reference. - {#syntax#}@import("root"){#endsyntax#} - Points to the root source file.
This is usually
src/main.zig
but it depends on what file is chosen to be built.
{#syntax#}@intCast(comptime DestType: type, int: anytype) DestType{#endsyntax#}
Converts an integer to another integer while keeping the same numerical value. Attempting to convert a number which is out of range of the destination type results in safety-protected {#link|Undefined Behavior#}.
{#code_begin|test_err|cast truncated bits#} test "integer cast panic" { var a: u16 = 0xabcd; var b: u8 = @intCast(u8, a); _ = b; } {#code_end#}To truncate the significant bits of a number out of range of the destination type, use {#link|@truncate#}.
If {#syntax#}T{#endsyntax#} is {#syntax#}comptime_int{#endsyntax#}, then this is semantically equivalent to {#link|Type Coercion#}.
{#header_close#} {#header_open|@intToEnum#}{#syntax#}@intToEnum(comptime DestType: type, integer: anytype) DestType{#endsyntax#}
Converts an integer into an {#link|enum#} value.
Attempting to convert an integer which represents no value in the chosen enum type invokes safety-checked {#link|Undefined Behavior#}.
{#see_also|@enumToInt#} {#header_close#} {#header_open|@intToError#}{#syntax#}@intToError(value: std.meta.Int(.unsigned, @sizeOf(anyerror) * 8)) anyerror{#endsyntax#}
Converts from the integer representation of an error into {#link|The Global Error Set#} type.
It is generally recommended to avoid this cast, as the integer representation of an error is not stable across source code changes.
Attempting to convert an integer that does not correspond to any error results in safety-protected {#link|Undefined Behavior#}.
{#see_also|@errorToInt#} {#header_close#} {#header_open|@intToFloat#}{#syntax#}@intToFloat(comptime DestType: type, int: anytype) DestType{#endsyntax#}
Converts an integer to the closest floating point representation. To convert the other way, use {#link|@floatToInt#}. This cast is always safe.
{#header_close#} {#header_open|@intToPtr#}{#syntax#}@intToPtr(comptime DestType: type, address: usize) DestType{#endsyntax#}
Converts an integer to a {#link|pointer|Pointers#}. To convert the other way, use {#link|@ptrToInt#}. Casting an address of 0 to a destination type which in not {#link|optional|Optional Pointers#} and does not have the {#syntax#}allowzero{#endsyntax#} attribute will result in a {#link|Pointer Cast Invalid Null#} panic when runtime safety checks are enabled.
If the destination pointer type does not allow address zero and {#syntax#}address{#endsyntax#} is zero, this invokes safety-checked {#link|Undefined Behavior#}.
{#header_close#} {#header_open|@max#}{#syntax#}@max(a: T, b: T) T{#endsyntax#}
Returns the maximum value of {#syntax#}a{#endsyntax#} and {#syntax#}b{#endsyntax#}. This builtin accepts integers, floats, and vectors of either. In the latter case, the operation is performed element wise.
NaNs are handled as follows: if one of the operands of a (pairwise) operation is NaN, the other operand is returned. If both operands are NaN, NaN is returned.
{#see_also|@min|Vectors#} {#header_close#} {#header_open|@memcpy#}{#syntax#}@memcpy(noalias dest: [*]u8, noalias source: [*]const u8, byte_count: usize){#endsyntax#}
This function copies bytes from one region of memory to another. {#syntax#}dest{#endsyntax#} and {#syntax#}source{#endsyntax#} are both pointers and must not overlap.
This function is a low level intrinsic with no safety mechanisms. Most code should not use this function, instead using something like this:
{#syntax#}for (source[0..byte_count]) |b, i| dest[i] = b;{#endsyntax#}
The optimizer is intelligent enough to turn the above snippet into a memcpy.
There is also a standard library function for this:
{#syntax#}const mem = @import("std").mem; mem.copy(u8, dest[0..byte_count], source[0..byte_count]);{#endsyntax#}{#header_close#} {#header_open|@memset#}
{#syntax#}@memset(dest: [*]u8, c: u8, byte_count: usize){#endsyntax#}
This function sets a region of memory to {#syntax#}c{#endsyntax#}. {#syntax#}dest{#endsyntax#} is a pointer.
This function is a low level intrinsic with no safety mechanisms. Most code should not use this function, instead using something like this:
{#syntax#}for (dest[0..byte_count]) |*b| b.* = c;{#endsyntax#}
The optimizer is intelligent enough to turn the above snippet into a memset.
There is also a standard library function for this:
{#syntax#}const mem = @import("std").mem; mem.set(u8, dest, c);{#endsyntax#}{#header_close#} {#header_open|@min#}
{#syntax#}@min(a: T, b: T) T{#endsyntax#}
Returns the minimum value of {#syntax#}a{#endsyntax#} and {#syntax#}b{#endsyntax#}. This builtin accepts integers, floats, and vectors of either. In the latter case, the operation is performed element wise.
NaNs are handled as follows: if one of the operands of a (pairwise) operation is NaN, the other operand is returned. If both operands are NaN, NaN is returned.
{#see_also|@max|Vectors#} {#header_close#} {#header_open|@wasmMemorySize#}{#syntax#}@wasmMemorySize(index: u32) u32{#endsyntax#}
This function returns the size of the Wasm memory identified by {#syntax#}index{#endsyntax#} as an unsigned value in units of Wasm pages. Note that each Wasm page is 64KB in size.
This function is a low level intrinsic with no safety mechanisms usually useful for allocator designers targeting Wasm. So unless you are writing a new allocator from scratch, you should use something like {#syntax#}@import("std").heap.WasmPageAllocator{#endsyntax#}.
{#see_also|@wasmMemoryGrow#} {#header_close#} {#header_open|@wasmMemoryGrow#}{#syntax#}@wasmMemoryGrow(index: u32, delta: u32) i32{#endsyntax#}
This function increases the size of the Wasm memory identified by {#syntax#}index{#endsyntax#} by {#syntax#}delta{#endsyntax#} in units of unsigned number of Wasm pages. Note that each Wasm page is 64KB in size. On success, returns previous memory size; on failure, if the allocation fails, returns -1.
This function is a low level intrinsic with no safety mechanisms usually useful for allocator designers targeting Wasm. So unless you are writing a new allocator from scratch, you should use something like {#syntax#}@import("std").heap.WasmPageAllocator{#endsyntax#}.
{#code_begin|test|wasmMemoryGrow#} const std = @import("std"); const native_arch = @import("builtin").target.cpu.arch; const expect = std.testing.expect; test "@wasmMemoryGrow" { if (native_arch != .wasm32) return error.SkipZigTest; var prev = @wasmMemorySize(0); try expect(prev == @wasmMemoryGrow(0, 1)); try expect(prev + 1 == @wasmMemorySize(0)); } {#code_end#} {#see_also|@wasmMemorySize#} {#header_close#} {#header_open|@mod#}{#syntax#}@mod(numerator: T, denominator: T) T{#endsyntax#}
Modulus division. For unsigned integers this is the same as {#syntax#}numerator % denominator{#endsyntax#}. Caller guarantees {#syntax#}denominator > 0{#endsyntax#}, otherwise the operation will result in a {#link|Remainder Division by Zero#} when runtime safety checks are enabled.
- {#syntax#}@mod(-5, 3) == 1{#endsyntax#}
- {#syntax#}(@divFloor(a, b) * b) + @mod(a, b) == a{#endsyntax#}
For a function that returns an error code, see {#syntax#}@import("std").math.mod{#endsyntax#}.
{#see_also|@rem#} {#header_close#} {#header_open|@mulWithOverflow#}{#syntax#}@mulWithOverflow(comptime T: type, a: T, b: T, result: *T) bool{#endsyntax#}
Performs {#syntax#}result.* = a * b{#endsyntax#}. If overflow or underflow occurs, stores the overflowed bits in {#syntax#}result{#endsyntax#} and returns {#syntax#}true{#endsyntax#}. If no overflow or underflow occurs, returns {#syntax#}false{#endsyntax#}.
{#header_close#} {#header_open|@panic#}{#syntax#}@panic(message: []const u8) noreturn{#endsyntax#}
Invokes the panic handler function. By default the panic handler function calls the public {#syntax#}panic{#endsyntax#} function exposed in the root source file, or if there is not one specified, the {#syntax#}std.builtin.default_panic{#endsyntax#} function from {#syntax#}std/builtin.zig{#endsyntax#}.
Generally it is better to use {#syntax#}@import("std").debug.panic{#endsyntax#}. However, {#syntax#}@panic{#endsyntax#} can be useful for 2 scenarios:
- From library code, calling the programmer's panic function if they exposed one in the root source file.
- When mixing C and Zig code, calling the canonical panic implementation across multiple .o files.
{#syntax#}@popCount(operand: anytype){#endsyntax#}
{#syntax#}@TypeOf(operand){#endsyntax#} must be an integer type.
{#syntax#}operand{#endsyntax#} may be an {#link|integer|Integers#} or {#link|vector|Vectors#}.
Counts the number of bits set in an integer.
If {#syntax#}operand{#endsyntax#} is a {#link|comptime#}-known integer, the return type is {#syntax#}comptime_int{#endsyntax#}. Otherwise, the return type is an unsigned integer or vector of unsigned integers with the minimum number of bits that can represent the bit count of the integer type.
{#see_also|@ctz|@clz#} {#header_close#} {#header_open|@prefetch#}{#syntax#}@prefetch(ptr: anytype, comptime options: std.builtin.PrefetchOptions){#endsyntax#}
This builtin tells the compiler to emit a prefetch instruction if supported by the target CPU. If the target CPU does not support the requested prefetch instruction, this builtin is a no-op. This function has no effect on the behavior of the program, only on the performance characteristics.
The {#syntax#}ptr{#endsyntax#} argument may be any pointer type and determines the memory address to prefetch. This function does not dereference the pointer, it is perfectly legal to pass a pointer to invalid memory to this function and no illegal behavior will result.
The {#syntax#}options{#endsyntax#} argument is the following struct:
{#code_begin|syntax|builtin#} /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const PrefetchOptions = struct { /// Whether the prefetch should prepare for a read or a write. rw: Rw = .read, /// 0 means no temporal locality. That is, the data can be immediately /// dropped from the cache after it is accessed. /// /// 3 means high temporal locality. That is, the data should be kept in /// the cache as it is likely to be accessed again soon. locality: u2 = 3, /// The cache that the prefetch should be preformed on. cache: Cache = .data, pub const Rw = enum { read, write, }; pub const Cache = enum { instruction, data, }; }; {#code_end#} {#header_close#} {#header_open|@ptrCast#}{#syntax#}@ptrCast(comptime DestType: type, value: anytype) DestType{#endsyntax#}
Converts a pointer of one type to a pointer of another type.
{#link|Optional Pointers#} are allowed. Casting an optional pointer which is {#link|null#} to a non-optional pointer invokes safety-checked {#link|Undefined Behavior#}.
{#header_close#} {#header_open|@ptrToInt#}{#syntax#}@ptrToInt(value: anytype) usize{#endsyntax#}
Converts {#syntax#}value{#endsyntax#} to a {#syntax#}usize{#endsyntax#} which is the address of the pointer. {#syntax#}value{#endsyntax#} can be {#syntax#}*T{#endsyntax#} or {#syntax#}?*T{#endsyntax#}.
To convert the other way, use {#link|@intToPtr#}
{#header_close#} {#header_open|@rem#}{#syntax#}@rem(numerator: T, denominator: T) T{#endsyntax#}
Remainder division. For unsigned integers this is the same as {#syntax#}numerator % denominator{#endsyntax#}. Caller guarantees {#syntax#}denominator > 0{#endsyntax#}, otherwise the operation will result in a {#link|Remainder Division by Zero#} when runtime safety checks are enabled.
- {#syntax#}@rem(-5, 3) == -2{#endsyntax#}
- {#syntax#}(@divTrunc(a, b) * b) + @rem(a, b) == a{#endsyntax#}
For a function that returns an error code, see {#syntax#}@import("std").math.rem{#endsyntax#}.
{#see_also|@mod#} {#header_close#} {#header_open|@returnAddress#}{#syntax#}@returnAddress() usize{#endsyntax#}
This function returns the address of the next machine code instruction that will be executed when the current function returns.
The implications of this are target-specific and not consistent across all platforms.
This function is only valid within function scope. If the function gets inlined into a calling function, the returned address will apply to the calling function.
{#header_close#} {#header_open|@select#}{#syntax#}@select(comptime T: type, pred: @Vector(len, bool), a: @Vector(len, T), b: @Vector(len, T)) @Vector(len, T){#endsyntax#}
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#}.
{#see_also|Vectors#} {#header_close#} {#header_open|@setAlignStack#}{#syntax#}@setAlignStack(comptime alignment: u29){#endsyntax#}
Ensures that a function will have a stack alignment of at least {#syntax#}alignment{#endsyntax#} bytes.
{#header_close#} {#header_open|@setCold#}{#syntax#}@setCold(comptime is_cold: bool){#endsyntax#}
Tells the optimizer that a function is rarely called.
{#header_close#} {#header_open|@setEvalBranchQuota#}{#syntax#}@setEvalBranchQuota(comptime new_quota: u32){#endsyntax#}
Changes the maximum number of backwards branches that compile-time code execution can use before giving up and making a compile error.
If the {#syntax#}new_quota{#endsyntax#} is smaller than the default quota ({#syntax#}1000{#endsyntax#}) or a previously explicitly set quota, it is ignored.
Example:
{#code_begin|test_err|evaluation exceeded 1000 backwards branches#} test "foo" { comptime { var i = 0; while (i < 1001) : (i += 1) {} } } {#code_end#}Now we use {#syntax#}@setEvalBranchQuota{#endsyntax#}:
{#code_begin|test|setEvalBranchQuota#} test "foo" { comptime { @setEvalBranchQuota(1001); var i = 0; while (i < 1001) : (i += 1) {} } } {#code_end#} {#see_also|comptime#} {#header_close#} {#header_open|@setFloatMode#}{#syntax#}@setFloatMode(comptime mode: @import("std").builtin.FloatMode){#endsyntax#}
Sets the floating point mode of the current scope. Possible values are:
{#code_begin|syntax#} pub const FloatMode = enum { Strict, Optimized, }; {#code_end#}- {#syntax#}Strict{#endsyntax#} (default) - Floating point operations follow strict IEEE compliance.
-
{#syntax#}Optimized{#endsyntax#} - Floating point operations may do all of the following:
- Assume the arguments and result are not NaN. Optimizations are required to retain defined behavior over NaNs, but the value of the result is undefined.
- Assume the arguments and result are not +/-Inf. Optimizations are required to retain defined behavior over +/-Inf, but the value of the result is undefined.
- Treat the sign of a zero argument or result as insignificant.
- Use the reciprocal of an argument rather than perform division.
- Perform floating-point contraction (e.g. fusing a multiply followed by an addition into a fused multiply-add).
- Perform algebraically equivalent transformations that may change results in floating point (e.g. reassociate).
-ffast-math
in GCC.
The floating point mode is inherited by child scopes, and can be overridden in any scope. You can set the floating point mode in a struct or module scope by using a comptime block.
{#see_also|Floating Point Operations#} {#header_close#} {#header_open|@setRuntimeSafety#}{#syntax#}@setRuntimeSafety(comptime safety_on: bool) void{#endsyntax#}
Sets whether runtime safety checks are enabled for the scope that contains the function call.
{#code_begin|test_safety|integer overflow#} {#code_release_fast#} test "@setRuntimeSafety" { // The builtin applies to the scope that it is called in. So here, integer overflow // will not be caught in ReleaseFast and ReleaseSmall modes: // var x: u8 = 255; // x += 1; // undefined behavior in ReleaseFast/ReleaseSmall modes. { // However this block has safety enabled, so safety checks happen here, // even in ReleaseFast and ReleaseSmall modes. @setRuntimeSafety(true); var x: u8 = 255; x += 1; { // The value can be overridden at any scope. So here integer overflow // would not be caught in any build mode. @setRuntimeSafety(false); // var x: u8 = 255; // x += 1; // undefined behavior in all build modes. } } } {#code_end#}Note: it is planned to replace
{#syntax#}@setRuntimeSafety{#endsyntax#} with @optimizeFor
{#syntax#}@shlExact(value: T, shift_amt: Log2T) T{#endsyntax#}
Performs the left shift operation ({#syntax#}<<{#endsyntax#}). For unsigned integers, the result is {#link|undefined#} if any 1 bits are shifted out. For signed integers, the result is {#link|undefined#} if any bits that disagree with the resultant sign bit are shifted out.
The type of {#syntax#}shift_amt{#endsyntax#} is an unsigned integer with {#syntax#}log2(@typeInfo(T).Int.bits){#endsyntax#} bits. This is because {#syntax#}shift_amt >= @typeInfo(T).Int.bits{#endsyntax#} is undefined behavior.
{#see_also|@shrExact|@shlWithOverflow#} {#header_close#} {#header_open|@shlWithOverflow#}{#syntax#}@shlWithOverflow(comptime T: type, a: T, shift_amt: Log2T, result: *T) bool{#endsyntax#}
Performs {#syntax#}result.* = a << b{#endsyntax#}. If overflow or underflow occurs, stores the overflowed bits in {#syntax#}result{#endsyntax#} and returns {#syntax#}true{#endsyntax#}. If no overflow or underflow occurs, returns {#syntax#}false{#endsyntax#}.
The type of {#syntax#}shift_amt{#endsyntax#} is an unsigned integer with {#syntax#}log2(@typeInfo(T).Int.bits){#endsyntax#} bits. This is because {#syntax#}shift_amt >= @typeInfo(T).Int.bits{#endsyntax#} is undefined behavior.
{#see_also|@shlExact|@shrExact#} {#header_close#} {#header_open|@shrExact#}{#syntax#}@shrExact(value: T, shift_amt: Log2T) T{#endsyntax#}
Performs the right shift operation ({#syntax#}>>{#endsyntax#}). Caller guarantees that the shift will not shift any 1 bits out.
The type of {#syntax#}shift_amt{#endsyntax#} is an unsigned integer with {#syntax#}log2(@typeInfo(T).Int.bits){#endsyntax#} bits. This is because {#syntax#}shift_amt >= @typeInfo(T).Int.bits{#endsyntax#} is undefined behavior.
{#see_also|@shlExact|@shlWithOverflow#} {#header_close#} {#header_open|@shuffle#}{#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#}
Constructs a new {#link|vector|Vectors#} by selecting elements from {#syntax#}a{#endsyntax#} and {#syntax#}b{#endsyntax#} based on {#syntax#}mask{#endsyntax#}.
Each element in {#syntax#}mask{#endsyntax#} selects an element from either {#syntax#}a{#endsyntax#} or {#syntax#}b{#endsyntax#}. Positive numbers select from {#syntax#}a{#endsyntax#} starting at 0. Negative values select from {#syntax#}b{#endsyntax#}, starting at {#syntax#}-1{#endsyntax#} and going down. It is recommended to use the {#syntax#}~{#endsyntax#} operator for indexes from {#syntax#}b{#endsyntax#} so that both indexes can start from {#syntax#}0{#endsyntax#} (i.e. {#syntax#}~@as(i32, 0){#endsyntax#} is {#syntax#}-1{#endsyntax#}).
For each element of {#syntax#}mask{#endsyntax#}, if it or the selected value from {#syntax#}a{#endsyntax#} or {#syntax#}b{#endsyntax#} is {#syntax#}undefined{#endsyntax#}, then the resulting element is {#syntax#}undefined{#endsyntax#}.
{#syntax#}a_len{#endsyntax#} and {#syntax#}b_len{#endsyntax#} may differ in length. Out-of-bounds element indexes in {#syntax#}mask{#endsyntax#} result in compile errors.
If {#syntax#}a{#endsyntax#} or {#syntax#}b{#endsyntax#} is {#syntax#}undefined{#endsyntax#}, it is equivalent to a vector of all {#syntax#}undefined{#endsyntax#} with the same length as the other vector. If both vectors are {#syntax#}undefined{#endsyntax#}, {#syntax#}@shuffle{#endsyntax#} returns a vector with all elements {#syntax#}undefined{#endsyntax#}.
{#syntax#}E{#endsyntax#} must be an {#link|integer|Integers#}, {#link|float|Floats#}, {#link|pointer|Pointers#}, or {#syntax#}bool{#endsyntax#}. The mask may be any vector length, and its length determines the result length.
{#code_begin|test|vector_shuffle#} const std = @import("std"); const expect = std.testing.expect; test "vector @shuffle" { const a = @Vector(7, u8){ 'o', 'l', 'h', 'e', 'r', 'z', 'w' }; const b = @Vector(4, u8){ 'w', 'd', '!', 'x' }; // To shuffle within a single vector, pass undefined as the second argument. // Notice that we can re-order, duplicate, or omit elements of the input vector const mask1 = @Vector(5, i32){ 2, 3, 1, 1, 0 }; const res1: @Vector(5, u8) = @shuffle(u8, a, undefined, mask1); try expect(std.mem.eql(u8, &@as([5]u8, res1), "hello")); // Combining two vectors const mask2 = @Vector(6, i32){ -1, 0, 4, 1, -2, -3 }; const res2: @Vector(6, u8) = @shuffle(u8, a, b, mask2); try expect(std.mem.eql(u8, &@as([6]u8, res2), "world!")); } {#code_end#} {#see_also|Vectors#} {#header_close#} {#header_open|@sizeOf#}{#syntax#}@sizeOf(comptime T: type) comptime_int{#endsyntax#}
This function returns the number of bytes it takes to store {#syntax#}T{#endsyntax#} in memory. The result is a target-specific compile time constant.
This size may contain padding bytes. If there were two consecutive T in memory, this would be the offset in bytes between element at index 0 and the element at index 1. For {#link|integer|Integers#}, consider whether you want to use {#syntax#}@sizeOf(T){#endsyntax#} or {#syntax#}@typeInfo(T).Int.bits{#endsyntax#}.
This function measures the size at runtime. For types that are disallowed at runtime, such as {#syntax#}comptime_int{#endsyntax#} and {#syntax#}type{#endsyntax#}, the result is {#syntax#}0{#endsyntax#}.
{#see_also|@bitSizeOf|@typeInfo#} {#header_close#} {#header_open|@splat#}{#syntax#}@splat(comptime len: u32, scalar: anytype) @Vector(len, @TypeOf(scalar)){#endsyntax#}
Produces a vector of length {#syntax#}len{#endsyntax#} where each element is the value {#syntax#}scalar{#endsyntax#}:
{#code_begin|test|vector_splat#} const std = @import("std"); const expect = std.testing.expect; test "vector @splat" { const scalar: u32 = 5; const result = @splat(4, scalar); comptime try expect(@TypeOf(result) == @Vector(4, u32)); try expect(std.mem.eql(u32, &@as([4]u32, result), &[_]u32{ 5, 5, 5, 5 })); } {#code_end#}{#syntax#}scalar{#endsyntax#} must be an {#link|integer|Integers#}, {#link|bool|Primitive Types#}, {#link|float|Floats#}, or {#link|pointer|Pointers#}.
{#see_also|Vectors|@shuffle#} {#header_close#} {#header_open|@reduce#}{#syntax#}@reduce(comptime op: std.builtin.ReduceOp, value: anytype) E{#endsyntax#}
Transforms a {#link|vector|Vectors#} into a scalar value (of type E
)
by performing a sequential horizontal reduction of its elements using the
specified operator {#syntax#}op{#endsyntax#}.
Not every operator is available for every vector element type:
- Every operator is available for {#link|integer|Integers#} vectors.
- {#syntax#}.And{#endsyntax#}, {#syntax#}.Or{#endsyntax#}, {#syntax#}.Xor{#endsyntax#} are additionally available for {#syntax#}bool{#endsyntax#} vectors,
- {#syntax#}.Min{#endsyntax#}, {#syntax#}.Max{#endsyntax#}, {#syntax#}.Add{#endsyntax#}, {#syntax#}.Mul{#endsyntax#} are additionally available for {#link|floating point|Floats#} vectors,
Note that {#syntax#}.Add{#endsyntax#} and {#syntax#}.Mul{#endsyntax#} reductions on integral types are wrapping; when applied on floating point types the operation associativity is preserved, unless the float mode is set to {#syntax#}Optimized{#endsyntax#}.
{#code_begin|test|vector_reduce#} const std = @import("std"); const expect = std.testing.expect; test "vector @reduce" { const value = @Vector(4, i32){ 1, -1, 1, -1 }; const result = value > @splat(4, @as(i32, 0)); // result is { true, false, true, false }; comptime try expect(@TypeOf(result) == @Vector(4, bool)); const is_all_true = @reduce(.And, result); comptime try expect(@TypeOf(is_all_true) == bool); try expect(is_all_true == false); } {#code_end#} {#see_also|Vectors|@setFloatMode#} {#header_close#} {#header_open|@src#}{#syntax#}@src() std.builtin.SourceLocation{#endsyntax#}
Returns a {#syntax#}SourceLocation{#endsyntax#} struct representing the function's name and location in the source code. This must be called in a function.
{#code_begin|test|source_location#} const std = @import("std"); const expect = std.testing.expect; test "@src" { try doTheTest(); } fn doTheTest() !void { const src = @src(); try expect(src.line == 9); try expect(src.column == 17); try expect(std.mem.endsWith(u8, src.fn_name, "doTheTest")); try expect(std.mem.endsWith(u8, src.file, "source_location.zig")); } {#code_end#} {#header_close#} {#header_open|@sqrt#}{#syntax#}@sqrt(value: anytype) @TypeOf(value){#endsyntax#}
Performs the square root of a floating point number. Uses a dedicated hardware instruction when available.
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that some float operations are not yet implemented for all float types.
{#header_close#} {#header_open|@sin#}{#syntax#}@sin(value: anytype) @TypeOf(value){#endsyntax#}
Sine trigonometric function on a floating point number. Uses a dedicated hardware instruction when available.
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that some float operations are not yet implemented for all float types.
{#header_close#} {#header_open|@cos#}{#syntax#}@cos(value: anytype) @TypeOf(value){#endsyntax#}
Cosine trigonometric function on a floating point number. Uses a dedicated hardware instruction when available.
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that some float operations are not yet implemented for all float types.
{#header_close#} {#header_open|@tan#}{#syntax#}@tan(value: anytype) @TypeOf(value){#endsyntax#}
Tangent trigonometric function on a floating point number. Uses a dedicated hardware instruction when available.
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that some float operations are not yet implemented for all float types.
{#header_close#} {#header_open|@exp#}{#syntax#}@exp(value: anytype) @TypeOf(value){#endsyntax#}
Base-e exponential function on a floating point number. Uses a dedicated hardware instruction when available.
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that some float operations are not yet implemented for all float types.
{#header_close#} {#header_open|@exp2#}{#syntax#}@exp2(value: anytype) @TypeOf(value){#endsyntax#}
Base-2 exponential function on a floating point number. Uses a dedicated hardware instruction when available.
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that some float operations are not yet implemented for all float types.
{#header_close#} {#header_open|@log#}{#syntax#}@log(value: anytype) @TypeOf(value){#endsyntax#}
Returns the natural logarithm of a floating point number. Uses a dedicated hardware instruction when available.
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that some float operations are not yet implemented for all float types.
{#header_close#} {#header_open|@log2#}{#syntax#}@log2(value: anytype) @TypeOf(value){#endsyntax#}
Returns the logarithm to the base 2 of a floating point number. Uses a dedicated hardware instruction when available.
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that some float operations are not yet implemented for all float types.
{#header_close#} {#header_open|@log10#}{#syntax#}@log10(value: anytype) @TypeOf(value){#endsyntax#}
Returns the logarithm to the base 10 of a floating point number. Uses a dedicated hardware instruction when available.
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that some float operations are not yet implemented for all float types.
{#header_close#} {#header_open|@fabs#}{#syntax#}@fabs(value: anytype) @TypeOf(value){#endsyntax#}
Returns the absolute value of a floating point number. Uses a dedicated hardware instruction when available.
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that some float operations are not yet implemented for all float types.
{#header_close#} {#header_open|@floor#}{#syntax#}@floor(value: anytype) @TypeOf(value){#endsyntax#}
Returns the largest integral value not greater than the given floating point number. Uses a dedicated hardware instruction when available.
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that some float operations are not yet implemented for all float types.
{#header_close#} {#header_open|@ceil#}{#syntax#}@ceil(value: anytype) @TypeOf(value){#endsyntax#}
Returns the smallest integral value not less than the given floating point number. Uses a dedicated hardware instruction when available.
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that some float operations are not yet implemented for all float types.
{#header_close#} {#header_open|@trunc#}{#syntax#}@trunc(value: anytype) @TypeOf(value){#endsyntax#}
Rounds the given floating point number to an integer, towards zero. Uses a dedicated hardware instruction when available.
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that some float operations are not yet implemented for all float types.
{#header_close#} {#header_open|@round#}{#syntax#}@round(value: anytype) @TypeOf(value){#endsyntax#}
Rounds the given floating point number to an integer, away from zero. Uses a dedicated hardware instruction when available.
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that some float operations are not yet implemented for all float types.
{#header_close#} {#header_open|@subWithOverflow#}{#syntax#}@subWithOverflow(comptime T: type, a: T, b: T, result: *T) bool{#endsyntax#}
Performs {#syntax#}result.* = a - b{#endsyntax#}. If overflow or underflow occurs, stores the overflowed bits in {#syntax#}result{#endsyntax#} and returns {#syntax#}true{#endsyntax#}. If no overflow or underflow occurs, returns {#syntax#}false{#endsyntax#}.
{#header_close#} {#header_open|@tagName#}{#syntax#}@tagName(value: anytype) [:0]const u8{#endsyntax#}
Converts an enum value or union value to a string literal representing the name.
If the enum is non-exhaustive and the tag value does not map to a name, it invokes safety-checked {#link|Undefined Behavior#}.
{#header_close#} {#header_open|@This#}{#syntax#}@This() type{#endsyntax#}
Returns the innermost struct, enum, or union that this function call is inside. This can be useful for an anonymous struct that needs to refer to itself:
{#code_begin|test|this_innermost#} const std = @import("std"); const expect = std.testing.expect; test "@This()" { var items = [_]i32{ 1, 2, 3, 4 }; const list = List(i32){ .items = items[0..] }; try expect(list.length() == 4); } fn List(comptime T: type) type { return struct { const Self = @This(); items: []T, fn length(self: Self) usize { return self.items.len; } }; } {#code_end#}When {#syntax#}@This(){#endsyntax#} is used at file scope, it returns a reference to the struct that corresponds to the current file.
{#header_close#} {#header_open|@truncate#}{#syntax#}@truncate(comptime T: type, integer: anytype) T{#endsyntax#}
This function truncates bits from an integer type, resulting in a smaller or same-sized integer type.
This function always truncates the significant bits of the integer, regardless of endianness on the target platform.
Calling {#syntax#}@truncate{#endsyntax#} on a number out of range of the destination type is well defined and working code:
{#code_begin|test|truncate#} const std = @import("std"); const expect = std.testing.expect; test "integer truncation" { var a: u16 = 0xabcd; var b: u8 = @truncate(u8, a); try expect(b == 0xcd); } {#code_end#}Use {#link|@intCast#} to convert numbers guaranteed to fit the destination type.
{#header_close#} {#header_open|@Type#}{#syntax#}@Type(comptime info: std.builtin.Type) type{#endsyntax#}
This function is the inverse of {#link|@typeInfo#}. It reifies type information into a {#syntax#}type{#endsyntax#}.
It is available for the following types:
- {#syntax#}type{#endsyntax#}
- {#syntax#}noreturn{#endsyntax#}
- {#syntax#}void{#endsyntax#}
- {#syntax#}bool{#endsyntax#}
- {#link|Integers#} - The maximum bit count for an integer type is {#syntax#}65535{#endsyntax#}.
- {#link|Floats#}
- {#link|Pointers#}
- {#syntax#}comptime_int{#endsyntax#}
- {#syntax#}comptime_float{#endsyntax#}
- {#syntax#}@TypeOf(undefined){#endsyntax#}
- {#syntax#}@TypeOf(null){#endsyntax#}
- {#link|Arrays#}
- {#link|Optionals#}
- {#link|Error Set Type#}
- {#link|Error Union Type#}
- {#link|Vectors#}
- {#link|opaque#}
- {#link|@Frame#}
- {#syntax#}anyframe{#endsyntax#}
- {#link|struct#}
- {#link|enum#}
- {#link|Enum Literals#}
- {#link|union#}
For these types, {#syntax#}@Type{#endsyntax#} is not available:
- {#link|Functions#}
- BoundFn
{#syntax#}@typeInfo(comptime T: type) std.builtin.Type{#endsyntax#}
Provides type reflection.
Type information of {#link|structs|struct#}, {#link|unions|union#}, {#link|enums|enum#}, and {#link|error sets|Error Set Type#} has fields which are guaranteed to be in the same order as appearance in the source file.
Type information of {#link|structs|struct#}, {#link|unions|union#}, {#link|enums|enum#}, and {#link|opaques|opaque#} has declarations, which are also guaranteed to be in the same order as appearance in the source file.
{#header_close#} {#header_open|@typeName#}{#syntax#}@typeName(T: type) *const [N:0]u8{#endsyntax#}
This function returns the string representation of a type, as an array. It is equivalent to a string literal of the type name. The returned type name is fully qualified with the parent namespace included as part of the type name with a series of dots.
{#header_close#} {#header_open|@TypeOf#}{#syntax#}@TypeOf(...) type{#endsyntax#}
{#syntax#}@TypeOf{#endsyntax#} is a special builtin function that takes any (nonzero) number of expressions as parameters and returns the type of the result, using {#link|Peer Type Resolution#}.
The expressions are evaluated, however they are guaranteed to have no runtime side-effects:
{#code_begin|test|no_runtime_side_effects#} const std = @import("std"); const expect = std.testing.expect; test "no runtime side effects" { var data: i32 = 0; const T = @TypeOf(foo(i32, &data)); comptime try expect(T == i32); try expect(data == 0); } fn foo(comptime T: type, ptr: *T) T { ptr.* += 1; return ptr.*; } {#code_end#} {#header_close#} {#header_open|@unionInit#}{#syntax#}@unionInit(comptime Union: type, comptime active_field_name: []const u8, init_expr) Union{#endsyntax#}
This is the same thing as {#link|union#} initialization syntax, except that the field name is a {#link|comptime#}-known value rather than an identifier token.
{#syntax#}@unionInit{#endsyntax#} forwards its {#link|result location|Result Location Semantics#} to {#syntax#}init_expr{#endsyntax#}.
{#header_close#} {#header_open|@Vector#}{#syntax#}@Vector(len: comptime_int, Element: type) type{#endsyntax#}
Creates {#link|Vectors#}.
{#header_close#} {#header_close#} {#header_open|Build Mode#}Zig has four build modes:
- {#link|Debug#} (default)
- {#link|ReleaseFast#}
- {#link|ReleaseSafe#}
- {#link|ReleaseSmall#}
To add standard build options to a build.zig
file:
This causes these options to be available:
- -Drelease-safe=[bool]
- Optimizations on and safety on
- -Drelease-fast=[bool]
- Optimizations on and safety off
- -Drelease-small=[bool]
- Size optimizations on and safety off
- Fast compilation speed
- Safety checks enabled
- Slow runtime performance
- Large binary size
- No reproducible build requirement
- Fast runtime performance
- Safety checks disabled
- Slow compilation speed
- Large binary size
- Reproducible build
- Medium runtime performance
- Safety checks enabled
- Slow compilation speed
- Large binary size
- Reproducible build
- Medium runtime performance
- Safety checks disabled
- Slow compilation speed
- Small binary size
- Reproducible build
Zig has a compile option --single-threaded which has the following effects:
- All {#link|Thread Local Variables#} are treated as regular {#link|Container Level Variables#}.
- The overhead of {#link|Async Functions#} becomes equivalent to function call overhead.
- The {#syntax#}@import("builtin").single_threaded{#endsyntax#} becomes {#syntax#}true{#endsyntax#} and therefore various userland APIs which read this variable become more efficient. For example {#syntax#}std.Mutex{#endsyntax#} becomes an empty data structure and all of its functions become no-ops.
Zig has many instances of undefined behavior. If undefined behavior is detected at compile-time, Zig emits a compile error and refuses to continue. Most undefined behavior that cannot be detected at compile-time can be detected at runtime. In these cases, Zig has safety checks. Safety checks can be disabled on a per-block basis with {#link|@setRuntimeSafety#}. The {#link|ReleaseFast#} and {#link|ReleaseSmall#} build modes disable all safety checks (except where overridden by {#link|@setRuntimeSafety#}) in order to facilitate optimizations.
When a safety check fails, Zig crashes with a stack trace, like this:
{#code_begin|test_err|reached unreachable code#} test "safety check" { unreachable; } {#code_end#} {#header_open|Reaching Unreachable Code#}At compile-time:
{#code_begin|test_err|reached unreachable code#} comptime { assert(false); } fn assert(ok: bool) void { if (!ok) unreachable; // assertion failure } {#code_end#}At runtime:
{#code_begin|exe_err#} const std = @import("std"); pub fn main() void { std.debug.assert(false); } {#code_end#} {#header_close#} {#header_open|Index out of Bounds#}At compile-time:
{#code_begin|test_err|index 5 outside array of length 5#} comptime { const array: [5]u8 = "hello".*; const garbage = array[5]; _ = garbage; } {#code_end#}At runtime:
{#code_begin|exe_err#} pub fn main() void { var x = foo("hello"); _ = x; } fn foo(x: []const u8) u8 { return x[5]; } {#code_end#} {#header_close#} {#header_open|Cast Negative Number to Unsigned Integer#}At compile-time:
{#code_begin|test_err|type 'u32' cannot represent integer value '-1'#} comptime { var value: i32 = -1; const unsigned = @intCast(u32, value); _ = unsigned; } {#code_end#}At runtime:
{#code_begin|exe_err#} const std = @import("std"); pub fn main() void { var value: i32 = -1; var unsigned = @intCast(u32, value); std.debug.print("value: {}\n", .{unsigned}); } {#code_end#}To obtain the maximum value of an unsigned integer, use {#syntax#}std.math.maxInt{#endsyntax#}.
{#header_close#} {#header_open|Cast Truncates Data#}At compile-time:
{#code_begin|test_err|type 'u8' cannot represent integer value '300'#} comptime { const spartan_count: u16 = 300; const byte = @intCast(u8, spartan_count); _ = byte; } {#code_end#}At runtime:
{#code_begin|exe_err#} const std = @import("std"); pub fn main() void { var spartan_count: u16 = 300; const byte = @intCast(u8, spartan_count); std.debug.print("value: {}\n", .{byte}); } {#code_end#}To truncate bits, use {#link|@truncate#}.
{#header_close#} {#header_open|Integer Overflow#} {#header_open|Default Operations#}The following operators can cause integer overflow:
- {#syntax#}+{#endsyntax#} (addition)
- {#syntax#}-{#endsyntax#} (subtraction)
- {#syntax#}-{#endsyntax#} (negation)
- {#syntax#}*{#endsyntax#} (multiplication)
- {#syntax#}/{#endsyntax#} (division)
- {#link|@divTrunc#} (division)
- {#link|@divFloor#} (division)
- {#link|@divExact#} (division)
Example with addition at compile-time:
{#code_begin|test_err|overflow of integer type 'u8' with value '256'#} comptime { var byte: u8 = 255; byte += 1; } {#code_end#}At runtime:
{#code_begin|exe_err#} const std = @import("std"); pub fn main() void { var byte: u8 = 255; byte += 1; std.debug.print("value: {}\n", .{byte}); } {#code_end#} {#header_close#} {#header_open|Standard Library Math Functions#}These functions provided by the standard library return possible errors.
- {#syntax#}@import("std").math.add{#endsyntax#}
- {#syntax#}@import("std").math.sub{#endsyntax#}
- {#syntax#}@import("std").math.mul{#endsyntax#}
- {#syntax#}@import("std").math.divTrunc{#endsyntax#}
- {#syntax#}@import("std").math.divFloor{#endsyntax#}
- {#syntax#}@import("std").math.divExact{#endsyntax#}
- {#syntax#}@import("std").math.shl{#endsyntax#}
Example of catching an overflow for addition:
{#code_begin|exe_err#} const math = @import("std").math; const print = @import("std").debug.print; pub fn main() !void { var byte: u8 = 255; byte = if (math.add(u8, byte, 1)) |result| result else |err| { print("unable to add one: {s}\n", .{@errorName(err)}); return err; }; print("result: {}\n", .{byte}); } {#code_end#} {#header_close#} {#header_open|Builtin Overflow Functions#}These builtins return a {#syntax#}bool{#endsyntax#} of whether or not overflow occurred, as well as returning the overflowed bits:
- {#link|@addWithOverflow#}
- {#link|@subWithOverflow#}
- {#link|@mulWithOverflow#}
- {#link|@shlWithOverflow#}
Example of {#link|@addWithOverflow#}:
{#code_begin|exe#} const print = @import("std").debug.print; pub fn main() void { var byte: u8 = 255; var result: u8 = undefined; if (@addWithOverflow(u8, byte, 10, &result)) { print("overflowed result: {}\n", .{result}); } else { print("result: {}\n", .{result}); } } {#code_end#} {#header_close#} {#header_open|Wrapping Operations#}These operations have guaranteed wraparound semantics.
- {#syntax#}+%{#endsyntax#} (wraparound addition)
- {#syntax#}-%{#endsyntax#} (wraparound subtraction)
- {#syntax#}-%{#endsyntax#} (wraparound negation)
- {#syntax#}*%{#endsyntax#} (wraparound multiplication)
At compile-time:
{#code_begin|test_err|operation caused overflow#} {#backend_stage1#} comptime { const x = @shlExact(@as(u8, 0b01010101), 2); _ = x; } {#code_end#}At runtime:
{#code_begin|exe_err#} const std = @import("std"); pub fn main() void { var x: u8 = 0b01010101; var y = @shlExact(x, 2); std.debug.print("value: {}\n", .{y}); } {#code_end#} {#header_close#} {#header_open|Exact Right Shift Overflow#}At compile-time:
{#code_begin|test_err|exact shift shifted out 1 bits#} {#backend_stage1#} comptime { const x = @shrExact(@as(u8, 0b10101010), 2); _ = x; } {#code_end#}At runtime:
{#code_begin|exe_err#} const std = @import("std"); pub fn main() void { var x: u8 = 0b10101010; var y = @shrExact(x, 2); std.debug.print("value: {}\n", .{y}); } {#code_end#} {#header_close#} {#header_open|Division by Zero#}At compile-time:
{#code_begin|test_err|division by zero#} comptime { const a: i32 = 1; const b: i32 = 0; const c = a / b; _ = c; } {#code_end#}At runtime:
{#code_begin|exe_err#} const std = @import("std"); pub fn main() void { var a: u32 = 1; var b: u32 = 0; var c = a / b; std.debug.print("value: {}\n", .{c}); } {#code_end#} {#header_close#} {#header_open|Remainder Division by Zero#}At compile-time:
{#code_begin|test_err|division by zero#} comptime { const a: i32 = 10; const b: i32 = 0; const c = a % b; _ = c; } {#code_end#}At runtime:
{#code_begin|exe_err#} const std = @import("std"); pub fn main() void { var a: u32 = 10; var b: u32 = 0; var c = a % b; std.debug.print("value: {}\n", .{c}); } {#code_end#} {#header_close#} {#header_open|Exact Division Remainder#}At compile-time:
{#code_begin|test_err|exact division had a remainder#} {#backend_stage1#} comptime { const a: u32 = 10; const b: u32 = 3; const c = @divExact(a, b); _ = c; } {#code_end#}At runtime:
{#code_begin|exe_err#} const std = @import("std"); pub fn main() void { var a: u32 = 10; var b: u32 = 3; var c = @divExact(a, b); std.debug.print("value: {}\n", .{c}); } {#code_end#} {#header_close#} {#header_open|Attempt to Unwrap Null#}At compile-time:
{#code_begin|test_err|unable to unwrap null#} comptime { const optional_number: ?i32 = null; const number = optional_number.?; _ = number; } {#code_end#}At runtime:
{#code_begin|exe_err#} const std = @import("std"); pub fn main() void { var optional_number: ?i32 = null; var number = optional_number.?; std.debug.print("value: {}\n", .{number}); } {#code_end#}One way to avoid this crash is to test for null instead of assuming non-null, with the {#syntax#}if{#endsyntax#} expression:
{#code_begin|exe|test#} const print = @import("std").debug.print; pub fn main() void { const optional_number: ?i32 = null; if (optional_number) |number| { print("got number: {}\n", .{number}); } else { print("it's null\n", .{}); } } {#code_end#} {#see_also|Optionals#} {#header_close#} {#header_open|Attempt to Unwrap Error#}At compile-time:
{#code_begin|test_err|caught unexpected error 'UnableToReturnNumber'#} comptime { const number = getNumberOrFail() catch unreachable; _ = number; } fn getNumberOrFail() !i32 { return error.UnableToReturnNumber; } {#code_end#}At runtime:
{#code_begin|exe_err#} const std = @import("std"); pub fn main() void { const number = getNumberOrFail() catch unreachable; std.debug.print("value: {}\n", .{number}); } fn getNumberOrFail() !i32 { return error.UnableToReturnNumber; } {#code_end#}One way to avoid this crash is to test for an error instead of assuming a successful result, with the {#syntax#}if{#endsyntax#} expression:
{#code_begin|exe#} const print = @import("std").debug.print; pub fn main() void { const result = getNumberOrFail(); if (result) |number| { print("got number: {}\n", .{number}); } else |err| { print("got error: {s}\n", .{@errorName(err)}); } } fn getNumberOrFail() !i32 { return error.UnableToReturnNumber; } {#code_end#} {#see_also|Errors#} {#header_close#} {#header_open|Invalid Error Code#}At compile-time:
{#code_begin|test_err|integer value '11' represents no error#} comptime { const err = error.AnError; const number = @errorToInt(err) + 10; const invalid_err = @intToError(number); _ = invalid_err; } {#code_end#}At runtime:
{#code_begin|exe_err#} const std = @import("std"); pub fn main() void { var err = error.AnError; var number = @errorToInt(err) + 500; var invalid_err = @intToError(number); std.debug.print("value: {}\n", .{invalid_err}); } {#code_end#} {#header_close#} {#header_open|Invalid Enum Cast#}At compile-time:
{#code_begin|test_err|enum 'test.Foo' has no tag with value '3'#} const Foo = enum { a, b, c, }; comptime { const a: u2 = 3; const b = @intToEnum(Foo, a); _ = b; } {#code_end#}At runtime:
{#code_begin|exe_err#} const std = @import("std"); const Foo = enum { a, b, c, }; pub fn main() void { var a: u2 = 3; var b = @intToEnum(Foo, a); std.debug.print("value: {s}\n", .{@tagName(b)}); } {#code_end#} {#header_close#} {#header_open|Invalid Error Set Cast#}At compile-time:
{#code_begin|test_err|'error.B' not a member of error set 'error{A,C}'#} const Set1 = error{ A, B, }; const Set2 = error{ A, C, }; comptime { _ = @errSetCast(Set2, Set1.B); } {#code_end#}At runtime:
{#code_begin|exe_err#} const std = @import("std"); const Set1 = error{ A, B, }; const Set2 = error{ A, C, }; pub fn main() void { foo(Set1.B); } fn foo(set1: Set1) void { const x = @errSetCast(Set2, set1); std.debug.print("value: {}\n", .{x}); } {#code_end#} {#header_close#} {#header_open|Incorrect Pointer Alignment#}At compile-time:
{#code_begin|test_err|pointer address 0x1 is not aligned to 4 bytes#} comptime { const ptr = @intToPtr(*align(1) i32, 0x1); const aligned = @alignCast(4, ptr); _ = aligned; } {#code_end#}At runtime:
{#code_begin|exe_err#} const mem = @import("std").mem; pub fn main() !void { var array align(4) = [_]u32{ 0x11111111, 0x11111111 }; const bytes = mem.sliceAsBytes(array[0..]); if (foo(bytes) != 0x11111111) return error.Wrong; } fn foo(bytes: []u8) u32 { const slice4 = bytes[1..5]; const int_slice = mem.bytesAsSlice(u32, @alignCast(4, slice4)); return int_slice[0]; } {#code_end#} {#header_close#} {#header_open|Wrong Union Field Access#}At compile-time:
{#code_begin|test_err|access of union field 'float' while field 'int' is active#} comptime { var f = Foo{ .int = 42 }; f.float = 12.34; } const Foo = union { float: f32, int: u32, }; {#code_end#}At runtime:
{#code_begin|exe_err#} const std = @import("std"); const Foo = union { float: f32, int: u32, }; pub fn main() void { var f = Foo{ .int = 42 }; bar(&f); } fn bar(f: *Foo) void { f.float = 12.34; std.debug.print("value: {}\n", .{f.float}); } {#code_end#}This safety is not available for {#syntax#}extern{#endsyntax#} or {#syntax#}packed{#endsyntax#} unions.
To change the active field of a union, assign the entire union, like this:
{#code_begin|exe#} const std = @import("std"); const Foo = union { float: f32, int: u32, }; pub fn main() void { var f = Foo{ .int = 42 }; bar(&f); } fn bar(f: *Foo) void { f.* = Foo{ .float = 12.34 }; std.debug.print("value: {}\n", .{f.float}); } {#code_end#}To change the active field of a union when a meaningful value for the field is not known, use {#link|undefined#}, like this:
{#code_begin|exe#} const std = @import("std"); const Foo = union { float: f32, int: u32, }; pub fn main() void { var f = Foo{ .int = 42 }; f = Foo{ .float = undefined }; bar(&f); std.debug.print("value: {}\n", .{f.float}); } fn bar(f: *Foo) void { f.float = 12.34; } {#code_end#} {#see_also|union|extern union#} {#header_close#} {#header_open|Out of Bounds Float to Integer Cast#}TODO
{#header_close#} {#header_open|Pointer Cast Invalid Null#}This happens when casting a pointer with the address 0 to a pointer which may not have the address 0. For example, {#link|C Pointers#}, {#link|Optional Pointers#}, and {#link|allowzero#} pointers allow address zero, but normal {#link|Pointers#} do not.
At compile-time:
{#code_begin|test_err|null pointer casted to type#} {#backend_stage1#} comptime { const opt_ptr: ?*i32 = null; const ptr = @ptrCast(*i32, opt_ptr); _ = ptr; } {#code_end#}At runtime:
{#code_begin|exe_err#} pub fn main() void { var opt_ptr: ?*i32 = null; var ptr = @ptrCast(*i32, opt_ptr); _ = ptr; } {#code_end#} {#header_close#} {#header_close#} {#header_open|Memory#}The Zig language performs no memory management on behalf of the programmer. This is why Zig has no runtime, and why Zig code works seamlessly in so many environments, including real-time software, operating system kernels, embedded devices, and low latency servers. As a consequence, Zig programmers must always be able to answer the question:
{#link|Where are the bytes?#}
Like Zig, the C programming language has manual memory management. However, unlike Zig,
C has a default allocator - malloc
, realloc
, and free
.
When linking against libc, Zig exposes this allocator with {#syntax#}std.heap.c_allocator{#endsyntax#}.
However, by convention, there is no default allocator in Zig. Instead, functions which need to
allocate accept an {#syntax#}Allocator{#endsyntax#} parameter. Likewise, data structures such as
{#syntax#}std.ArrayList{#endsyntax#} accept an {#syntax#}Allocator{#endsyntax#} parameter in
their initialization functions:
In the above example, 100 bytes of stack memory are used to initialize a {#syntax#}FixedBufferAllocator{#endsyntax#}, which is then passed to a function. As a convenience there is a global {#syntax#}FixedBufferAllocator{#endsyntax#} available for quick tests at {#syntax#}std.testing.allocator{#endsyntax#}, which will also perform basic leak detection.
Zig has a general purpose allocator available to be imported with {#syntax#}std.heap.GeneralPurposeAllocator{#endsyntax#}. However, it is still recommended to follow the {#link|Choosing an Allocator#} guide.
{#header_open|Choosing an Allocator#}What allocator to use depends on a number of factors. Here is a flow chart to help you decide:
- Are you making a library? In this case, best to accept an {#syntax#}Allocator{#endsyntax#} as a parameter and allow your library's users to decide what allocator to use.
- Are you linking libc? In this case, {#syntax#}std.heap.c_allocator{#endsyntax#} is likely the right choice, at least for your main allocator.
- Is the maximum number of bytes that you will need bounded by a number known at {#link|comptime#}? In this case, use {#syntax#}std.heap.FixedBufferAllocator{#endsyntax#} or {#syntax#}std.heap.ThreadSafeFixedBufferAllocator{#endsyntax#} depending on whether you need thread-safety or not.
- Is your program a command line application which runs from start to end without any fundamental cyclical pattern (such as a video game main loop, or a web server request handler), such that it would make sense to free everything at once at the end? In this case, it is recommended to follow this pattern: {#code_begin|exe|cli_allocation#} const std = @import("std"); pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const ptr = try allocator.create(i32); std.debug.print("ptr={*}\n", .{ptr}); } {#code_end#} When using this kind of allocator, there is no need to free anything manually. Everything gets freed at once with the call to {#syntax#}arena.deinit(){#endsyntax#}.
- Are the allocations part of a cyclical pattern such as a video game main loop, or a web server request handler? If the allocations can all be freed at once, at the end of the cycle, for example once the video game frame has been fully rendered, or the web server request has been served, then {#syntax#}std.heap.ArenaAllocator{#endsyntax#} is a great candidate. As demonstrated in the previous bullet point, this allows you to free entire arenas at once. Note also that if an upper bound of memory can be established, then {#syntax#}std.heap.FixedBufferAllocator{#endsyntax#} can be used as a further optimization.
- Are you writing a test, and you want to make sure {#syntax#}error.OutOfMemory{#endsyntax#} is handled correctly? In this case, use {#syntax#}std.testing.FailingAllocator{#endsyntax#}.
- Are you writing a test? In this case, use {#syntax#}std.testing.allocator{#endsyntax#}.
- Finally, if none of the above apply, you need a general purpose allocator. Zig's general purpose allocator is available as a function that takes a {#link|comptime#} {#link|struct#} of configuration options and returns a type. Generally, you will set up one {#syntax#}std.heap.GeneralPurposeAllocator{#endsyntax#} in your main function, and then pass it or sub-allocators around to various parts of your application.
- You can also consider {#link|Implementing an Allocator#}.
String literals such as {#syntax#}"foo"{#endsyntax#} are in the global constant data section. This is why it is an error to pass a string literal to a mutable slice, like this:
{#code_begin|test_err|expected type '[]u8', found '*const [5:0]u8'#} fn foo(s: []u8) void { _ = s; } test "string literal to mutable slice" { foo("hello"); } {#code_end#}However if you make the slice constant, then it works:
{#code_begin|test|strlit#} fn foo(s: []const u8) void { _ = s; } test "string literal to constant slice" { foo("hello"); } {#code_end#}Just like string literals, {#syntax#}const{#endsyntax#} declarations, when the value is known at {#link|comptime#}, are stored in the global constant data section. Also {#link|Compile Time Variables#} are stored in the global constant data section.
{#syntax#}var{#endsyntax#} declarations inside functions are stored in the function's stack frame. Once a function returns, any {#link|Pointers#} to variables in the function's stack frame become invalid references, and dereferencing them becomes unchecked {#link|Undefined Behavior#}.
{#syntax#}var{#endsyntax#} declarations at the top level or in {#link|struct#} declarations are stored in the global data section.
The location of memory allocated with {#syntax#}allocator.alloc{#endsyntax#} or {#syntax#}allocator.create{#endsyntax#} is determined by the allocator's implementation.
TODO: thread local variables
{#header_close#} {#header_open|Implementing an Allocator#}Zig programmers can implement their own allocators by fulfilling the Allocator interface. In order to do this one must read carefully the documentation comments in std/mem.zig and then supply a {#syntax#}allocFn{#endsyntax#} and a {#syntax#}resizeFn{#endsyntax#}.
There are many example allocators to look at for inspiration. Look at std/heap.zig and {#syntax#}std.heap.GeneralPurposeAllocator{#endsyntax#}.
{#header_close#} {#header_open|Heap Allocation Failure#}Many programming languages choose to handle the possibility of heap allocation failure by unconditionally crashing. By convention, Zig programmers do not consider this to be a satisfactory solution. Instead, {#syntax#}error.OutOfMemory{#endsyntax#} represents heap allocation failure, and Zig libraries return this error code whenever heap allocation failure prevented an operation from completing successfully.
Some have argued that because some operating systems such as Linux have memory overcommit enabled by default, it is pointless to handle heap allocation failure. There are many problems with this reasoning:
- Only some operating systems have an overcommit feature.
- Linux has it enabled by default, but it is configurable.
- Windows does not overcommit.
- Embedded systems do not have overcommit.
- Hobby operating systems may or may not have overcommit.
- For real-time systems, not only is there no overcommit, but typically the maximum amount of memory per application is determined ahead of time.
- When writing a library, one of the main goals is code reuse. By making code handle allocation failure correctly, a library becomes eligible to be reused in more contexts.
- Although some software has grown to depend on overcommit being enabled, its existence is the source of countless user experience disasters. When a system with overcommit enabled, such as Linux on default settings, comes close to memory exhaustion, the system locks up and becomes unusable. At this point, the OOM Killer selects an application to kill based on heuristics. This non-deterministic decision often results in an important process being killed, and often fails to return the system back to working order.
Recursion is a fundamental tool in modeling software. However it has an often-overlooked problem: unbounded memory allocation.
Recursion is an area of active experimentation in Zig and so the documentation here is not final. You can read a summary of recursion status in the 0.3.0 release notes.
The short summary is that currently recursion works normally as you would expect. Although Zig code is not yet protected from stack overflow, it is planned that a future version of Zig will provide such protection, with some degree of cooperation from Zig code required.
{#header_close#} {#header_open|Lifetime and Ownership#}It is the Zig programmer's responsibility to ensure that a {#link|pointer|Pointers#} is not accessed when the memory pointed to is no longer available. Note that a {#link|slice|Slices#} is a form of pointer, in that it references other memory.
In order to prevent bugs, there are some helpful conventions to follow when dealing with pointers. In general, when a function returns a pointer, the documentation for the function should explain who "owns" the pointer. This concept helps the programmer decide when it is appropriate, if ever, to free the pointer.
For example, the function's documentation may say "caller owns the returned memory", in which case the code that calls the function must have a plan for when to free that memory. Probably in this situation, the function will accept an {#syntax#}Allocator{#endsyntax#} parameter.
Sometimes the lifetime of a pointer may be more complicated. For example, the {#syntax#}std.ArrayList(T).items{#endsyntax#} slice has a lifetime that remains valid until the next time the list is resized, such as by appending new elements.
The API documentation for functions and data structures should take great care to explain the ownership and lifetime semantics of pointers. Ownership determines whose responsibility it is to free the memory referenced by the pointer, and lifetime determines the point at which the memory becomes inaccessible (lest {#link|Undefined Behavior#} occur).
{#header_close#} {#header_close#} {#header_open|Compile Variables#}Compile variables are accessible by importing the {#syntax#}"builtin"{#endsyntax#} package, which the compiler makes available to every Zig source file. It contains compile-time constants such as the current target, endianness, and release mode.
{#code_begin|syntax#} const builtin = @import("builtin"); const separator = if (builtin.os.tag == .windows) '\\' else '/'; {#code_end#}Example of what is imported with {#syntax#}@import("builtin"){#endsyntax#}:
{#builtin#} {#see_also|Build Mode#} {#header_close#} {#header_open|Root Source File#}TODO: explain how root source file finds other files
TODO: pub fn main
TODO: pub fn panic
TODO: if linking with libc you can use export fn main
TODO: order independent top level declarations
TODO: lazy analysis
TODO: using comptime { _ = @import() }
{#header_close#} {#header_open|Zig Build System#}The Zig Build System provides a cross-platform, dependency-free way to declare the logic required to build a project. With this system, the logic to build a project is written in a build.zig file, using the Zig Build System API to declare and configure build artifacts and other tasks.
Some examples of tasks the build system can help with:
- Creating build artifacts by executing the Zig compiler. This includes building Zig source code as well as C and C++ source code.
- Capturing user-configured options and using those options to configure the build.
- Surfacing build configuration as {#link|comptime#} values by providing a file that can be {#link|imported|@import#} by Zig code.
- Caching build artifacts to avoid unnecessarily repeating steps.
- Executing build artifacts or system-installed tools.
- Running tests and verifying the output of executing a build artifact matches the expected value.
- Running
zig fmt
on a codebase or a subset of it. - Custom tasks.
To use the build system, run zig build --help to see a command-line usage help menu. This will include project-specific options that were declared in the build.zig script.
{#header_open|Building an Executable#}This build.zig
file is automatically generated
by zig init-exe.
This build.zig
file is automatically generated
by zig init-lib.
{#syntax#} lib.addCSourceFile("src/lib.c", &[_][]const u8{ "-Wall", "-Wextra", "-Werror", }); {#endsyntax#}{#header_close#} {#header_close#} {#header_open|C#}
Although Zig is independent of C, and, unlike most other languages, does not depend on libc, Zig acknowledges the importance of interacting with existing C code.
There are a few ways that Zig facilitates C interop.
{#header_open|C Type Primitives#}These have guaranteed C ABI compatibility and can be used like any other type.
- {#syntax#}c_short{#endsyntax#}
- {#syntax#}c_ushort{#endsyntax#}
- {#syntax#}c_int{#endsyntax#}
- {#syntax#}c_uint{#endsyntax#}
- {#syntax#}c_long{#endsyntax#}
- {#syntax#}c_ulong{#endsyntax#}
- {#syntax#}c_longlong{#endsyntax#}
- {#syntax#}c_ulonglong{#endsyntax#}
- {#syntax#}c_longdouble{#endsyntax#}
To interop with the C {#syntax#}void{#endsyntax#} type, use {#syntax#}anyopaque{#endsyntax#}.
{#see_also|Primitive Types#} {#header_close#} {#header_open|Import from C Header File#}
The {#syntax#}@cImport{#endsyntax#} builtin function can be used
to directly import symbols from .h
files:
The {#syntax#}@cImport{#endsyntax#} function takes an expression as a parameter.
This expression is evaluated at compile-time and is used to control
preprocessor directives and include multiple .h
files:
- -I: Specify a search directory for include files. May be used multiple times. Equivalent to clang's -I flag. The current directory is not included by default; use -I. to include it.
- -D: Define a preprocessor macro. Equivalent to clang's -D flag.
- -cflags [flags] --: Pass arbitrary additional command line flags to clang. Note: the list of flags must end with --
- -target: The {#link|target triple|Targets#} for the translated Zig code. If no target is specified, the current host target will be used.
Important! When translating C code with zig translate-c, you must use the same -target triple that you will use when compiling the translated code. In addition, you must ensure that the -cflags used, if any, match the cflags used by code on the target system. Using the incorrect -target or -cflags could result in clang or Zig parse failures, or subtle ABI incompatibilities when linking with C code.
{#syntax_block|c|varytarget.h#}long FOO = __LONG_MAX__;{#end_syntax_block#} {#shell_samp#}$ zig translate-c -target thumb-freestanding-gnueabihf varytarget.h|grep FOO pub export var FOO: c_long = 2147483647; $ zig translate-c -target x86_64-macos-gnu varytarget.h|grep FOO pub export var FOO: c_long = 9223372036854775807;{#end_shell_samp#} {#syntax_block|c|varycflags.h#}enum FOO { BAR }; int do_something(enum FOO foo); {#end_syntax_block#} {#shell_samp#}$ zig translate-c varycflags.h|grep -B1 do_something pub const enum_FOO = c_uint; pub extern fn do_something(foo: enum_FOO) c_int; $ zig translate-c -cflags -fshort-enums -- varycflags.h|grep -B1 do_something pub const enum_FOO = u8; pub extern fn do_something(foo: enum_FOO) c_int;{#end_shell_samp#} {#header_close#} {#header_open|@cImport vs translate-c#}{#syntax#}@cImport{#endsyntax#} and zig translate-c use the same underlying C translation functionality, so on a technical level they are equivalent. In practice, {#syntax#}@cImport{#endsyntax#} is useful as a way to quickly and easily access numeric constants, typedefs, and record types without needing any extra setup. If you need to pass {#link|cflags|Using -target and -cflags#} to clang, or if you would like to edit the translated code, it is recommended to use zig translate-c and save the results to a file. Common reasons for editing the generated code include: changing {#syntax#}anytype{#endsyntax#} parameters in function-like macros to more specific types; changing {#syntax#}[*c]T{#endsyntax#} pointers to {#syntax#}[*]T{#endsyntax#} or {#syntax#}*T{#endsyntax#} pointers for improved type safety; and {#link|enabling or disabling runtime safety|@setRuntimeSafety#} within specific functions.
{#header_close#} {#see_also|Targets|C Type Primitives|Pointers|C Pointers|Import from C Header File|@cInclude|@cImport|@setRuntimeSafety#} {#header_close#} {#header_open|C Translation Caching#}The C translation feature (whether used via zig translate-c or {#syntax#}@cImport{#endsyntax#}) integrates with the Zig caching system. Subsequent runs with the same source file, target, and cflags will use the cache instead of repeatedly translating the same code.
To see where the cached files are stored when compiling code that uses {#syntax#}@cImport{#endsyntax#}, use the --verbose-cimport flag:
{#code_begin|exe|verbose#} {#link_libc#} {#code_verbose_cimport#} const c = @cImport({ @cDefine("_NO_CRT_STDIO_INLINE", "1"); @cInclude("stdio.h"); }); pub fn main() void { _ = c; } {#code_end#}
cimport.h
contains the file to translate (constructed from calls to
{#syntax#}@cInclude{#endsyntax#}, {#syntax#}@cDefine{#endsyntax#}, and {#syntax#}@cUndef{#endsyntax#}),
cimport.h.d
is the list of file dependencies, and
cimport.zig
contains the translated output.
Some C constructs cannot be translated to Zig - for example, goto, structs with bitfields, and token-pasting macros. Zig employs demotion to allow translation to continue in the face of non-translatable entities.
Demotion comes in three varieties - {#link|opaque#}, extern, and {#syntax#}@compileError{#endsyntax#}. C structs and unions that cannot be translated correctly will be translated as {#syntax#}opaque{}{#endsyntax#}. Functions that contain opaque types or code constructs that cannot be translated will be demoted to {#syntax#}extern{#endsyntax#} declarations. Thus, non-translatable types can still be used as pointers, and non-translatable functions can be called so long as the linker is aware of the compiled function.
{#syntax#}@compileError{#endsyntax#} is used when top-level definitions (global variables, function prototypes, macros) cannot be translated or demoted. Since Zig uses lazy analysis for top-level declarations, untranslatable entities will not cause a compile error in your code unless you actually use them.
{#see_also|opaque|extern|@compileError#} {#header_close#} {#header_open|C Macros#}C Translation makes a best-effort attempt to translate function-like macros into equivalent Zig functions. Since C macros operate at the level of lexical tokens, not all C macros can be translated to Zig. Macros that cannot be translated will be demoted to {#syntax#}@compileError{#endsyntax#}. Note that C code which uses macros will be translated without any additional issues (since Zig operates on the pre-processed source with macros expanded). It is merely the macros themselves which may not be translatable to Zig.
Consider the following example:
{#syntax_block|c|macro.c#}#define MAKELOCAL(NAME, INIT) int NAME = INIT int foo(void) { MAKELOCAL(a, 1); MAKELOCAL(b, 2); return a + b; } {#end_syntax_block#} {#shell_samp#}$ zig translate-c macro.c > macro.zig{#end_shell_samp#} {#code_begin|syntax|macro#} pub export fn foo() c_int { var a: c_int = 1; var b: c_int = 2; return a + b; } pub const MAKELOCAL = @compileError("unable to translate C expr: unexpected token .Equal"); // macro.c:1:9 {#code_end#}Note that {#syntax#}foo{#endsyntax#} was translated correctly despite using a non-translatable macro. {#syntax#}MAKELOCAL{#endsyntax#} was demoted to {#syntax#}@compileError{#endsyntax#} since it cannot be expressed as a Zig function; this simply means that you cannot directly use {#syntax#}MAKELOCAL{#endsyntax#} from Zig.
{#see_also|@compileError#} {#header_close#} {#header_open|C Pointers#}This type is to be avoided whenever possible. The only valid reason for using a C pointer is in auto-generated code from translating C code.
When importing C header files, it is ambiguous whether pointers should be translated as single-item pointers ({#syntax#}*T{#endsyntax#}) or many-item pointers ({#syntax#}[*]T{#endsyntax#}). C pointers are a compromise so that Zig code can utilize translated header files directly.
{#syntax#}[*c]T{#endsyntax#} - C pointer.
- Supports all the syntax of the other two pointer types.
- Coerces to other pointer types, as well as {#link|Optional Pointers#}. When a C pointer is coerced to a non-optional pointer, safety-checked {#link|Undefined Behavior#} occurs if the address is 0.
- Allows address 0. On non-freestanding targets, dereferencing address 0 is safety-checked {#link|Undefined Behavior#}. Optional C pointers introduce another bit to keep track of null, just like {#syntax#}?usize{#endsyntax#}. Note that creating an optional C pointer is unnecessary as one can use normal {#link|Optional Pointers#}.
- Supports {#link|Type Coercion#} to and from integers.
- Supports comparison with integers.
- Does not support Zig-only pointer attributes such as alignment. Use normal {#link|Pointers#} please!
When a C pointer is pointing to a single struct (not an array), dereference the C pointer to access the struct's fields or member data. That syntax looks like this:
{#syntax#}ptr_to_struct.*.struct_member{#endsyntax#}
This is comparable to doing {#syntax#}->{#endsyntax#} in C.
When a C pointer is pointing to an array of structs, the syntax reverts to this:
{#syntax#}ptr_to_struct_array[index].struct_member{#endsyntax#}
{#header_close#} {#header_open|Exporting a C Library#}One of the primary use cases for Zig is exporting a library with the C ABI for other programming languages to call into. The {#syntax#}export{#endsyntax#} keyword in front of functions, variables, and types causes them to be part of the library API:
{#code_begin|syntax|mathtest#} export fn add(a: i32, b: i32) i32 { return a + b; } {#code_end#}To make a static library:
{#shell_samp#}$ zig build-lib mathtest.zig{#end_shell_samp#}To make a shared library:
{#shell_samp#}$ zig build-lib mathtest.zig -dynamic{#end_shell_samp#}Here is an example with the {#link|Zig Build System#}:
{#syntax_block|c|test.c#}// This header is generated by zig from mathtest.zig #include "mathtest.h" #includeYou can mix Zig object files with any other object files that respect the C ABI. Example:
{#code_begin|syntax|base64#} const base64 = @import("std").base64; export fn decode_base_64( dest_ptr: [*]u8, dest_len: usize, source_ptr: [*]const u8, source_len: usize, ) usize { const src = source_ptr[0..source_len]; const dest = dest_ptr[0..dest_len]; const base64_decoder = base64.standard.Decoder; const decoded_size = base64_decoder.calcSizeForSlice(src) catch unreachable; base64_decoder.decode(dest[0..decoded_size], src) catch unreachable; return decoded_size; } {#code_end#} {#syntax_block|c|test.c#}// This header is generated by zig from base64.zig #include "base64.h" #includeZig supports building for WebAssembly out of the box.
{#header_open|Freestanding#}For host environments like the web browser and nodejs, build as a dynamic library using the freestanding OS target. Here's an example of running Zig code compiled to WebAssembly with nodejs.
{#code_begin|lib|math#} {#target_wasm#} {#link_mode_dynamic#} extern fn print(i32) void; export fn add(a: i32, b: i32) void { print(a + b); } {#code_end#} {#syntax_block|javascript|test.js#}const fs = require('fs'); const source = fs.readFileSync("./math.wasm"); const typedArray = new Uint8Array(source); WebAssembly.instantiate(typedArray, { env: { print: (result) => { console.log(`The result is ${result}`); } }}).then(result => { const add = result.instance.exports.add; add(1, 2); });{#end_syntax_block#} {#shell_samp#}$ node test.js The result is 3{#end_shell_samp#} {#header_close#} {#header_open|WASI#}Zig's support for WebAssembly System Interface (WASI) is under active development. Example of using the standard library and reading command line arguments:
{#code_begin|exe|args#} {#target_wasi#} const std = @import("std"); pub fn main() !void { var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; const gpa = general_purpose_allocator.allocator(); const args = try std.process.argsAlloc(gpa); defer std.process.argsFree(gpa, args); for (args) |arg, i| { std.debug.print("{}: {s}\n", .{ i, arg }); } } {#code_end#} {#shell_samp#}$ wasmtime args.wasm 123 hello 0: args.wasm 1: 123 2: hello{#end_shell_samp#}A more interesting example would be extracting the list of preopens from the runtime. This is now supported in the standard library via {#syntax#}std.fs.wasi.PreopenList{#endsyntax#}:
{#code_begin|exe|preopens#} {#target_wasi#} const std = @import("std"); const PreopenList = std.fs.wasi.PreopenList; pub fn main() !void { var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; const gpa = general_purpose_allocator.allocator(); var preopens = PreopenList.init(gpa); defer preopens.deinit(); try preopens.populate(null); for (preopens.asSlice()) |preopen, i| { std.debug.print("{}: {}\n", .{ i, preopen }); } } {#code_end#} {#shell_samp#}$ wasmtime --dir=. preopens.wasm 0: Preopen{ .fd = 3, .type = PreopenType{ .Dir = '.' } } {#end_shell_samp#} {#header_close#} {#header_close#} {#header_open|Targets#}
Zig supports generating code for all targets that LLVM supports. Here is
what it looks like to execute zig targets
on a Linux x86_64
computer:
The Zig Standard Library ({#syntax#}@import("std"){#endsyntax#}) has architecture, environment, and operating system abstractions, and thus takes additional work to support more platforms. Not all standard library code requires operating system abstractions, however, so things such as generic data structures work on all above platforms.
The current list of targets supported by the Zig Standard Library is:
- Linux x86_64
- Windows x86_64
- macOS x86_64
These coding conventions are not enforced by the compiler, but they are shipped in this documentation along with the compiler in order to provide a point of reference, should anyone wish to point to an authority on agreed upon Zig coding style.
{#header_open|Whitespace#}- 4 space indentation
- Open braces on same line, unless you need to wrap.
- If a list of things is longer than 2, put each item on its own line and exercise the ability to put an extra comma at the end.
- Line length: aim for 100; use common sense.
Roughly speaking: {#syntax#}camelCaseFunctionName{#endsyntax#}, {#syntax#}TitleCaseTypeName{#endsyntax#}, {#syntax#}snake_case_variable_name{#endsyntax#}. More precisely:
- If {#syntax#}x{#endsyntax#} is a {#syntax#}type{#endsyntax#} then {#syntax#}x{#endsyntax#} should be {#syntax#}TitleCase{#endsyntax#}, unless it is a {#syntax#}struct{#endsyntax#} with 0 fields and is never meant to be instantiated, in which case it is considered to be a "namespace" and uses {#syntax#}snake_case{#endsyntax#}.
- If {#syntax#}x{#endsyntax#} is callable, and {#syntax#}x{#endsyntax#}'s return type is {#syntax#}type{#endsyntax#}, then {#syntax#}x{#endsyntax#} should be {#syntax#}TitleCase{#endsyntax#}.
- If {#syntax#}x{#endsyntax#} is otherwise callable, then {#syntax#}x{#endsyntax#} should be {#syntax#}camelCase{#endsyntax#}.
- Otherwise, {#syntax#}x{#endsyntax#} should be {#syntax#}snake_case{#endsyntax#}.
Acronyms, initialisms, proper nouns, or any other word that has capitalization rules in written English are subject to naming conventions just like any other word. Even acronyms that are only 2 letters long are subject to these conventions.
File names fall into two categories: types and namespaces. If the file
(implicitly a struct) has top level fields, it should be named like any
other struct with fields using TitleCase
. Otherwise,
it should use snake_case
. Directory names should be
snake_case
.
These are general rules of thumb; if it makes sense to do something different, do what makes sense. For example, if there is an established convention such as {#syntax#}ENOENT{#endsyntax#}, follow the established convention.
{#header_close#} {#header_open|Examples#} {#syntax_block|zig|style_example.zig#} const namespace_name = @import("dir_name/file_name.zig"); const TypeName = @import("dir_name/TypeName.zig"); var global_var: i32 = undefined; const const_name = 42; const primitive_type_alias = f32; const string_alias = []u8; const StructName = struct { field: i32, }; const StructAlias = StructName; fn functionName(param_name: TypeName) void { var functionPointer = functionName; functionPointer(); functionPointer = otherFunction; functionPointer(); } const functionAlias = functionName; fn ListTemplateFunction(comptime ChildType: type, comptime fixed_size: usize) type { return List(ChildType, fixed_size); } fn ShortList(comptime T: type, comptime n: usize) type { return struct { field_name: [n]T, fn methodName() void {} }; } // The word XML loses its casing when used in Zig identifiers. const xml_document = \\ \\See the {#link|Zig Standard Library#} for more examples.
{#header_close#} {#header_open|Doc Comment Guidance#}- Omit any information that is redundant based on the name of the thing being documented.
- Duplicating information onto multiple similar functions is encouraged because it helps IDEs and other tools provide better help text.
- Use the word assume to indicate invariants that cause {#link|Undefined Behavior#} when violated.
- Use the word assert to indicate invariants that cause safety-checked {#link|Undefined Behavior#} when violated.
Zig source code is encoded in UTF-8. An invalid UTF-8 byte sequence results in a compile error.
Throughout all zig source code (including in comments), some code points are never allowed:
- Ascii control characters, except for U+000a (LF), U+000d (CR), and U+0009 (HT): U+0000 - U+0008, U+000b - U+000c, U+000e - U+0001f, U+007f.
- Non-Ascii Unicode line endings: U+0085 (NEL), U+2028 (LS), U+2029 (PS).
LF (byte value 0x0a, code point U+000a, {#syntax#}'\n'{#endsyntax#}) is the line terminator in Zig source code. This byte value terminates every line of zig source code except the last line of the file. It is recommended that non-empty source files end with an empty line, which means the last byte would be 0x0a (LF).
Each LF may be immediately preceded by a single CR (byte value 0x0d, code point U+000d, {#syntax#}'\r'{#endsyntax#}) to form a Windows style line ending, but this is discouraged. A CR in any other context is not allowed.
HT hard tabs (byte value 0x09, code point U+0009, {#syntax#}'\t'{#endsyntax#}) are interchangeable with SP spaces (byte value 0x20, code point U+0020, {#syntax#}' '{#endsyntax#}) as a token separator, but use of hard tabs is discouraged. See {#link|Grammar#}.
Note that running zig fmt on a source file will implement all recommendations mentioned here. Note also that the stage1 compiler does not yet support CR or HT control characters.
Note that a tool reading Zig source code can make assumptions if the source code is assumed to be correct Zig code.
For example, when identifying the ends of lines, a tool can use a naive search such as /\n/
,
or an advanced
search such as /\r\n?|[\n\u0085\u2028\u2029]/
, and in either case line endings will be correctly identified.
For another example, when identifying the whitespace before the first token on a line,
a tool can either use a naive search such as /[ \t]/
,
or an advanced search such as /\s/
,
and in either case whitespace will be correctly identified.
Keyword | Description |
---|---|
{#syntax#}align{#endsyntax#} |
{#syntax#}align{#endsyntax#} can be used to specify the alignment of a pointer.
It can also be used after a variable or function declaration to specify the alignment of pointers to that variable or function.
|
{#syntax#}allowzero{#endsyntax#} |
The pointer attribute {#syntax#}allowzero{#endsyntax#} allows a pointer to have address zero.
|
{#syntax#}and{#endsyntax#} |
The boolean operator {#syntax#}and{#endsyntax#}.
|
{#syntax#}anyframe{#endsyntax#} |
{#syntax#}anyframe{#endsyntax#} can be used as a type for variables which hold pointers to function frames.
|
{#syntax#}anytype{#endsyntax#} |
Function parameters can be declared with {#syntax#}anytype{#endsyntax#} in place of the type.
The type will be inferred where the function is called.
|
{#syntax#}asm{#endsyntax#} |
{#syntax#}asm{#endsyntax#} begins an inline assembly expression. This allows for directly controlling the machine code generated on compilation.
|
{#syntax#}async{#endsyntax#} |
{#syntax#}async{#endsyntax#} can be used before a function call to get a pointer to the function's frame when it suspends.
|
{#syntax#}await{#endsyntax#} |
{#syntax#}await{#endsyntax#} can be used to suspend the current function until the frame provided after the {#syntax#}await{#endsyntax#} completes.
{#syntax#}await{#endsyntax#} copies the value returned from the target function's frame to the caller.
|
{#syntax#}break{#endsyntax#} |
{#syntax#}break{#endsyntax#} can be used with a block label to return a value from the block.
It can also be used to exit a loop before iteration completes naturally.
|
{#syntax#}catch{#endsyntax#} |
{#syntax#}catch{#endsyntax#} can be used to evaluate an expression if the expression before it evaluates to an error.
The expression after the {#syntax#}catch{#endsyntax#} can optionally capture the error value.
|
{#syntax#}comptime{#endsyntax#} |
{#syntax#}comptime{#endsyntax#} before a declaration can be used to label variables or function parameters as known at compile time.
It can also be used to guarantee an expression is run at compile time.
|
{#syntax#}const{#endsyntax#} |
{#syntax#}const{#endsyntax#} declares a variable that can not be modified.
Used as a pointer attribute, it denotes the value referenced by the pointer cannot be modified.
|
{#syntax#}continue{#endsyntax#} |
{#syntax#}continue{#endsyntax#} can be used in a loop to jump back to the beginning of the loop.
|
{#syntax#}defer{#endsyntax#} |
{#syntax#}defer{#endsyntax#} will execute an expression when control flow leaves the current block.
|
{#syntax#}else{#endsyntax#} |
{#syntax#}else{#endsyntax#} can be used to provide an alternate branch for {#syntax#}if{#endsyntax#}, {#syntax#}switch{#endsyntax#},
{#syntax#}while{#endsyntax#}, and {#syntax#}for{#endsyntax#} expressions.
|
{#syntax#}enum{#endsyntax#} |
{#syntax#}enum{#endsyntax#} defines an enum type.
|
{#syntax#}errdefer{#endsyntax#} |
{#syntax#}errdefer{#endsyntax#} will execute an expression when control flow leaves the current block if the function returns an error, the errdefer expression can capture the unwrapped value.
|
{#syntax#}error{#endsyntax#} |
{#syntax#}error{#endsyntax#} defines an error type.
|
{#syntax#}export{#endsyntax#} |
{#syntax#}export{#endsyntax#} makes a function or variable externally visible in the generated object file.
Exported functions default to the C calling convention.
|
{#syntax#}extern{#endsyntax#} |
{#syntax#}extern{#endsyntax#} can be used to declare a function or variable that will be resolved at link time, when linking statically
or at runtime, when linking dynamically.
|
{#syntax#}fn{#endsyntax#} |
{#syntax#}fn{#endsyntax#} declares a function.
|
{#syntax#}for{#endsyntax#} |
A {#syntax#}for{#endsyntax#} expression can be used to iterate over the elements of a slice, array, or tuple.
|
{#syntax#}if{#endsyntax#} |
An {#syntax#}if{#endsyntax#} expression can test boolean expressions, optional values, or error unions.
For optional values or error unions, the if expression can capture the unwrapped value.
|
{#syntax#}inline{#endsyntax#} |
{#syntax#}inline{#endsyntax#} can be used to label a loop expression such that it will be unrolled at compile time.
It can also be used to force a function to be inlined at all call sites.
|
{#syntax#}noalias{#endsyntax#} |
The {#syntax#}noalias{#endsyntax#} keyword.
|
{#syntax#}nosuspend{#endsyntax#} |
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.
In particular, inside a {#syntax#}nosuspend{#endsyntax#} scope:
|
{#syntax#}or{#endsyntax#} |
The boolean operator {#syntax#}or{#endsyntax#}.
|
{#syntax#}orelse{#endsyntax#} |
{#syntax#}orelse{#endsyntax#} can be used to evaluate an expression if the expression before it evaluates to null.
|
{#syntax#}packed{#endsyntax#} |
The {#syntax#}packed{#endsyntax#} keyword before a struct definition changes the struct's in-memory layout
to the guaranteed {#syntax#}packed{#endsyntax#} layout.
|
{#syntax#}pub{#endsyntax#} |
The {#syntax#}pub{#endsyntax#} in front of a top level declaration makes the declaration available
to reference from a different file than the one it is declared in.
|
{#syntax#}resume{#endsyntax#} |
{#syntax#}resume{#endsyntax#} will continue execution of a function frame after the point the function was suspended.
|
{#syntax#}return{#endsyntax#} |
{#syntax#}return{#endsyntax#} exits a function with a value.
|
{#syntax#}linksection{#endsyntax#} |
The {#syntax#}linksection{#endsyntax#} keyword.
|
{#syntax#}struct{#endsyntax#} |
{#syntax#}struct{#endsyntax#} defines a struct.
|
{#syntax#}suspend{#endsyntax#} |
{#syntax#}suspend{#endsyntax#} will cause control flow to return to the call site or resumer of the function.
{#syntax#}suspend{#endsyntax#} can also be used before a block within a function,
to allow the function access to its frame before control flow returns to the call site.
|
{#syntax#}switch{#endsyntax#} |
A {#syntax#}switch{#endsyntax#} expression can be used to test values of a common type.
{#syntax#}switch{#endsyntax#} cases can capture field values of a {#link|Tagged union#}.
|
{#syntax#}test{#endsyntax#} |
The {#syntax#}test{#endsyntax#} keyword can be used to denote a top-level block of code
used to make sure behavior meets expectations.
|
{#syntax#}threadlocal{#endsyntax#} |
{#syntax#}threadlocal{#endsyntax#} can be used to specify a variable as thread-local.
|
{#syntax#}try{#endsyntax#} |
{#syntax#}try{#endsyntax#} evaluates an error union expression.
If it is an error, it returns from the current function with the same error.
Otherwise, the expression results in the unwrapped value.
|
{#syntax#}union{#endsyntax#} |
{#syntax#}union{#endsyntax#} defines a union.
|
{#syntax#}unreachable{#endsyntax#} |
{#syntax#}unreachable{#endsyntax#} can be used to assert that control flow will never happen upon a particular location.
Depending on the build mode, {#syntax#}unreachable{#endsyntax#} may emit a panic.
|
{#syntax#}usingnamespace{#endsyntax#} |
{#syntax#}usingnamespace{#endsyntax#} is a top-level declaration that imports all the public declarations of the operand,
which must be a struct, union, or enum, into the current scope.
|
{#syntax#}var{#endsyntax#} |
{#syntax#}var{#endsyntax#} declares a variable that may be modified.
|
{#syntax#}volatile{#endsyntax#} |
{#syntax#}volatile{#endsyntax#} can be used to denote loads or stores of a pointer have side effects.
It can also modify an inline assembly expression to denote it has side effects.
|
{#syntax#}while{#endsyntax#} |
A {#syntax#}while{#endsyntax#} expression can be used to repeatedly test a boolean, optional, or error union expression,
and cease looping when that expression evaluates to false, null, or an error, respectively.
|
A container in Zig is any syntactical construct that acts as a namespace to hold {#link|variable|Container Level Variables#} and {#link|function|Functions#} declarations. Containers are also type definitions which can be instantiated. {#link|Structs|struct#}, {#link|enums|enum#}, {#link|unions|union#}, {#link|opaques|opaque#}, and even Zig source files themselves are containers.
Although containers (except Zig source files) use curly braces to surround their definition, they should not be confused with {#link|blocks|Blocks#} or functions. Containers do not contain statements.
{#header_close#} {#header_open|Grammar#} {#syntax_block|peg|grammar.y#}Root <- skip container_doc_comment? ContainerMembers eof # *** Top level *** ContainerMembers <- ContainerDeclarations (ContainerField COMMA)* (ContainerField / ContainerDeclarations) ContainerDeclarations <- TestDecl ContainerDeclarations / TopLevelComptime ContainerDeclarations / doc_comment? KEYWORD_pub? TopLevelDecl ContainerDeclarations / TestDecl <- doc_comment? KEYWORD_test STRINGLITERALSINGLE? Block TopLevelComptime <- doc_comment? KEYWORD_comptime BlockExpr TopLevelDecl <- (KEYWORD_export / KEYWORD_extern STRINGLITERALSINGLE? / (KEYWORD_inline / KEYWORD_noinline))? FnProto (SEMICOLON / Block) / (KEYWORD_export / KEYWORD_extern STRINGLITERALSINGLE?)? KEYWORD_threadlocal? VarDecl / KEYWORD_usingnamespace Expr SEMICOLON FnProto <- KEYWORD_fn IDENTIFIER? LPAREN ParamDeclList RPAREN ByteAlign? LinkSection? CallConv? EXCLAMATIONMARK? TypeExpr VarDecl <- (KEYWORD_const / KEYWORD_var) IDENTIFIER (COLON TypeExpr)? ByteAlign? LinkSection? (EQUAL Expr)? SEMICOLON ContainerField <- doc_comment? KEYWORD_comptime? IDENTIFIER (COLON (KEYWORD_anytype / TypeExpr) ByteAlign?)? (EQUAL Expr)? # *** Block Level *** Statement <- KEYWORD_comptime? VarDecl / KEYWORD_comptime BlockExprStatement / KEYWORD_nosuspend BlockExprStatement / KEYWORD_suspend BlockExprStatement / KEYWORD_defer BlockExprStatement / KEYWORD_errdefer Payload? BlockExprStatement / IfStatement / LabeledStatement / SwitchExpr / AssignExpr SEMICOLON IfStatement <- IfPrefix BlockExpr ( KEYWORD_else Payload? Statement )? / IfPrefix AssignExpr ( SEMICOLON / KEYWORD_else Payload? Statement ) LabeledStatement <- BlockLabel? (Block / LoopStatement) LoopStatement <- KEYWORD_inline? (ForStatement / WhileStatement) ForStatement <- ForPrefix BlockExpr ( KEYWORD_else Statement )? / ForPrefix AssignExpr ( SEMICOLON / KEYWORD_else Statement ) WhileStatement <- WhilePrefix BlockExpr ( KEYWORD_else Payload? Statement )? / WhilePrefix AssignExpr ( SEMICOLON / KEYWORD_else Payload? Statement ) BlockExprStatement <- BlockExpr / AssignExpr SEMICOLON BlockExpr <- BlockLabel? Block # *** Expression Level *** AssignExpr <- Expr (AssignOp Expr)? Expr <- BoolOrExpr BoolOrExpr <- BoolAndExpr (KEYWORD_or BoolAndExpr)* BoolAndExpr <- CompareExpr (KEYWORD_and CompareExpr)* CompareExpr <- BitwiseExpr (CompareOp BitwiseExpr)? BitwiseExpr <- BitShiftExpr (BitwiseOp BitShiftExpr)* BitShiftExpr <- AdditionExpr (BitShiftOp AdditionExpr)* AdditionExpr <- MultiplyExpr (AdditionOp MultiplyExpr)* MultiplyExpr <- PrefixExpr (MultiplyOp PrefixExpr)* PrefixExpr <- PrefixOp* PrimaryExpr PrimaryExpr <- AsmExpr / IfExpr / KEYWORD_break BreakLabel? Expr? / KEYWORD_comptime Expr / KEYWORD_nosuspend Expr / KEYWORD_continue BreakLabel? / KEYWORD_resume Expr / KEYWORD_return Expr? / BlockLabel? LoopExpr / Block / CurlySuffixExpr IfExpr <- IfPrefix Expr (KEYWORD_else Payload? Expr)? Block <- LBRACE Statement* RBRACE LoopExpr <- KEYWORD_inline? (ForExpr / WhileExpr) ForExpr <- ForPrefix Expr (KEYWORD_else Expr)? WhileExpr <- WhilePrefix Expr (KEYWORD_else Payload? Expr)? CurlySuffixExpr <- TypeExpr InitList? InitList <- LBRACE FieldInit (COMMA FieldInit)* COMMA? RBRACE / LBRACE Expr (COMMA Expr)* COMMA? RBRACE / LBRACE RBRACE TypeExpr <- PrefixTypeOp* ErrorUnionExpr ErrorUnionExpr <- SuffixExpr (EXCLAMATIONMARK TypeExpr)? SuffixExpr <- KEYWORD_async PrimaryTypeExpr SuffixOp* FnCallArguments / PrimaryTypeExpr (SuffixOp / FnCallArguments)* PrimaryTypeExpr <- BUILTINIDENTIFIER FnCallArguments / CHAR_LITERAL / ContainerDecl / DOT IDENTIFIER / DOT InitList / ErrorSetDecl / FLOAT / FnProto / GroupedExpr / LabeledTypeExpr / IDENTIFIER / IfTypeExpr / INTEGER / KEYWORD_comptime TypeExpr / KEYWORD_error DOT IDENTIFIER / KEYWORD_anyframe / KEYWORD_unreachable / STRINGLITERAL / SwitchExpr ContainerDecl <- (KEYWORD_extern / KEYWORD_packed)? ContainerDeclAuto ErrorSetDecl <- KEYWORD_error LBRACE IdentifierList RBRACE GroupedExpr <- LPAREN Expr RPAREN IfTypeExpr <- IfPrefix TypeExpr (KEYWORD_else Payload? TypeExpr)? LabeledTypeExpr <- BlockLabel Block / BlockLabel? LoopTypeExpr LoopTypeExpr <- KEYWORD_inline? (ForTypeExpr / WhileTypeExpr) ForTypeExpr <- ForPrefix TypeExpr (KEYWORD_else TypeExpr)? WhileTypeExpr <- WhilePrefix TypeExpr (KEYWORD_else Payload? TypeExpr)? SwitchExpr <- KEYWORD_switch LPAREN Expr RPAREN LBRACE SwitchProngList RBRACE # *** Assembly *** AsmExpr <- KEYWORD_asm KEYWORD_volatile? LPAREN Expr AsmOutput? RPAREN AsmOutput <- COLON AsmOutputList AsmInput? AsmOutputItem <- LBRACKET IDENTIFIER RBRACKET STRINGLITERAL LPAREN (MINUSRARROW TypeExpr / IDENTIFIER) RPAREN AsmInput <- COLON AsmInputList AsmClobbers? AsmInputItem <- LBRACKET IDENTIFIER RBRACKET STRINGLITERAL LPAREN Expr RPAREN AsmClobbers <- COLON StringList # *** Helper grammar *** BreakLabel <- COLON IDENTIFIER BlockLabel <- IDENTIFIER COLON FieldInit <- DOT IDENTIFIER EQUAL Expr WhileContinueExpr <- COLON LPAREN AssignExpr RPAREN LinkSection <- KEYWORD_linksection LPAREN Expr RPAREN # Fn specific CallConv <- KEYWORD_callconv LPAREN Expr RPAREN ParamDecl <- doc_comment? (KEYWORD_noalias / KEYWORD_comptime)? (IDENTIFIER COLON)? ParamType / DOT3 ParamType <- KEYWORD_anytype / TypeExpr # Control flow prefixes IfPrefix <- KEYWORD_if LPAREN Expr RPAREN PtrPayload? WhilePrefix <- KEYWORD_while LPAREN Expr RPAREN PtrPayload? WhileContinueExpr? ForPrefix <- KEYWORD_for LPAREN Expr RPAREN PtrIndexPayload # Payloads Payload <- PIPE IDENTIFIER PIPE PtrPayload <- PIPE ASTERISK? IDENTIFIER PIPE PtrIndexPayload <- PIPE ASTERISK? IDENTIFIER (COMMA IDENTIFIER)? PIPE # Switch specific SwitchProng <- SwitchCase EQUALRARROW PtrPayload? AssignExpr SwitchCase <- SwitchItem (COMMA SwitchItem)* COMMA? / KEYWORD_else SwitchItem <- Expr (DOT3 Expr)? # Operators AssignOp <- ASTERISKEQUAL / SLASHEQUAL / PERCENTEQUAL / PLUSEQUAL / MINUSEQUAL / LARROW2EQUAL / RARROW2EQUAL / AMPERSANDEQUAL / CARETEQUAL / PIPEEQUAL / ASTERISKPERCENTEQUAL / PLUSPERCENTEQUAL / MINUSPERCENTEQUAL / EQUAL CompareOp <- EQUALEQUAL / EXCLAMATIONMARKEQUAL / LARROW / RARROW / LARROWEQUAL / RARROWEQUAL BitwiseOp <- AMPERSAND / CARET / PIPE / KEYWORD_orelse / KEYWORD_catch Payload? BitShiftOp <- LARROW2 / RARROW2 AdditionOp <- PLUS / MINUS / PLUS2 / PLUSPERCENT / MINUSPERCENT MultiplyOp <- PIPE2 / ASTERISK / SLASH / PERCENT / ASTERISK2 / ASTERISKPERCENT PrefixOp <- EXCLAMATIONMARK / MINUS / TILDE / MINUSPERCENT / AMPERSAND / KEYWORD_try / KEYWORD_await PrefixTypeOp <- QUESTIONMARK / KEYWORD_anyframe MINUSRARROW / SliceTypeStart (ByteAlign / KEYWORD_const / KEYWORD_volatile / KEYWORD_allowzero)* / PtrTypeStart (KEYWORD_align LPAREN Expr (COLON INTEGER COLON INTEGER)? RPAREN / KEYWORD_const / KEYWORD_volatile / KEYWORD_allowzero)* / ArrayTypeStart SuffixOp <- LBRACKET Expr (DOT2 (Expr? (COLON Expr)?)?)? RBRACKET / DOT IDENTIFIER / DOTASTERISK / DOTQUESTIONMARK FnCallArguments <- LPAREN ExprList RPAREN # Ptr specific SliceTypeStart <- LBRACKET (COLON Expr)? RBRACKET PtrTypeStart <- ASTERISK / ASTERISK2 / LBRACKET ASTERISK (LETTERC / COLON Expr)? RBRACKET ArrayTypeStart <- LBRACKET Expr (COLON Expr)? RBRACKET # ContainerDecl specific ContainerDeclAuto <- ContainerDeclType LBRACE container_doc_comment? ContainerMembers RBRACE ContainerDeclType <- KEYWORD_struct / KEYWORD_opaque / KEYWORD_enum (LPAREN Expr RPAREN)? / KEYWORD_union (LPAREN (KEYWORD_enum (LPAREN Expr RPAREN)? / Expr) RPAREN)? # Alignment ByteAlign <- KEYWORD_align LPAREN Expr RPAREN # Lists IdentifierList <- (doc_comment? IDENTIFIER COMMA)* (doc_comment? IDENTIFIER)? SwitchProngList <- (SwitchProng COMMA)* SwitchProng? AsmOutputList <- (AsmOutputItem COMMA)* AsmOutputItem? AsmInputList <- (AsmInputItem COMMA)* AsmInputItem? StringList <- (STRINGLITERAL COMMA)* STRINGLITERAL? ParamDeclList <- (ParamDecl COMMA)* ParamDecl? ExprList <- (Expr COMMA)* Expr? # *** Tokens *** eof <- !. bin <- [01] bin_ <- '_'? bin oct <- [0-7] oct_ <- '_'? oct hex <- [0-9a-fA-F] hex_ <- '_'? hex dec <- [0-9] dec_ <- '_'? dec bin_int <- bin bin_* oct_int <- oct oct_* dec_int <- dec dec_* hex_int <- hex hex_* ox80_oxBF <- [\200-\277] oxF4 <- '\364' ox80_ox8F <- [\200-\217] oxF1_oxF3 <- [\361-\363] oxF0 <- '\360' ox90_0xBF <- [\220-\277] oxEE_oxEF <- [\356-\357] oxED <- '\355' ox80_ox9F <- [\200-\237] oxE1_oxEC <- [\341-\354] oxE0 <- '\340' oxA0_oxBF <- [\240-\277] oxC2_oxDF <- [\302-\337] # From https://lemire.me/blog/2018/05/09/how-quickly-can-you-check-that-a-string-is-valid-unicode-utf-8/ # First Byte Second Byte Third Byte Fourth Byte # [0x00,0x7F] # [0xC2,0xDF] [0x80,0xBF] # 0xE0 [0xA0,0xBF] [0x80,0xBF] # [0xE1,0xEC] [0x80,0xBF] [0x80,0xBF] # 0xED [0x80,0x9F] [0x80,0xBF] # [0xEE,0xEF] [0x80,0xBF] [0x80,0xBF] # 0xF0 [0x90,0xBF] [0x80,0xBF] [0x80,0xBF] # [0xF1,0xF3] [0x80,0xBF] [0x80,0xBF] [0x80,0xBF] # 0xF4 [0x80,0x8F] [0x80,0xBF] [0x80,0xBF] mb_utf8_literal <- oxF4 ox80_ox8F ox80_oxBF ox80_oxBF / oxF1_oxF3 ox80_oxBF ox80_oxBF ox80_oxBF / oxF0 ox90_0xBF ox80_oxBF ox80_oxBF / oxEE_oxEF ox80_oxBF ox80_oxBF / oxED ox80_ox9F ox80_oxBF / oxE1_oxEC ox80_oxBF ox80_oxBF / oxE0 oxA0_oxBF ox80_oxBF / oxC2_oxDF ox80_oxBF ascii_char_not_nl_slash_squote <- [\000-\011\013-\046-\050-\133\135-\177] char_escape <- "\\x" hex hex / "\\u{" hex+ "}" / "\\" [nr\\t'"] char_char <- mb_utf8_literal / char_escape / ascii_char_not_nl_slash_squote string_char <- char_escape / [^\\"\n] container_doc_comment <- ('//!' [^\n]* [ \n]*)+ doc_comment <- ('///' [^\n]* [ \n]*)+ line_comment <- '//' ![!/][^\n]* / '////' [^\n]* line_string <- ("\\\\" [^\n]* [ \n]*)+ skip <- ([ \n] / line_comment)* CHAR_LITERAL <- "'" char_char "'" skip FLOAT <- "0x" hex_int "." hex_int ([pP] [-+]? dec_int)? skip / dec_int "." dec_int ([eE] [-+]? dec_int)? skip / "0x" hex_int [pP] [-+]? dec_int skip / dec_int [eE] [-+]? dec_int skip INTEGER <- "0b" bin_int skip / "0o" oct_int skip / "0x" hex_int skip / dec_int skip STRINGLITERALSINGLE <- "\"" string_char* "\"" skip STRINGLITERAL <- STRINGLITERALSINGLE / (line_string skip)+ IDENTIFIER <- !keyword [A-Za-z_] [A-Za-z0-9_]* skip / "@\"" string_char* "\"" skip BUILTINIDENTIFIER <- "@"[A-Za-z_][A-Za-z0-9_]* skip AMPERSAND <- '&' ![=] skip AMPERSANDEQUAL <- '&=' skip ASTERISK <- '*' ![*%=] skip ASTERISK2 <- '**' skip ASTERISKEQUAL <- '*=' skip ASTERISKPERCENT <- '*%' ![=] skip ASTERISKPERCENTEQUAL <- '*%=' skip CARET <- '^' ![=] skip CARETEQUAL <- '^=' skip COLON <- ':' skip COMMA <- ',' skip DOT <- '.' ![*.?] skip DOT2 <- '..' ![.] skip DOT3 <- '...' skip DOTASTERISK <- '.*' skip DOTQUESTIONMARK <- '.?' skip EQUAL <- '=' ![>=] skip EQUALEQUAL <- '==' skip EQUALRARROW <- '=>' skip EXCLAMATIONMARK <- '!' ![=] skip EXCLAMATIONMARKEQUAL <- '!=' skip LARROW <- '<' ![<=] skip LARROW2 <- '<<' ![=] skip LARROW2EQUAL <- '<<=' skip LARROWEQUAL <- '<=' skip LBRACE <- '{' skip LBRACKET <- '[' skip LPAREN <- '(' skip MINUS <- '-' ![%=>] skip MINUSEQUAL <- '-=' skip MINUSPERCENT <- '-%' ![=] skip MINUSPERCENTEQUAL <- '-%=' skip MINUSRARROW <- '->' skip PERCENT <- '%' ![=] skip PERCENTEQUAL <- '%=' skip PIPE <- '|' ![|=] skip PIPE2 <- '||' skip PIPEEQUAL <- '|=' skip PLUS <- '+' ![%+=] skip PLUS2 <- '++' skip PLUSEQUAL <- '+=' skip PLUSPERCENT <- '+%' ![=] skip PLUSPERCENTEQUAL <- '+%=' skip LETTERC <- 'c' skip QUESTIONMARK <- '?' skip RARROW <- '>' ![>=] skip RARROW2 <- '>>' ![=] skip RARROW2EQUAL <- '>>=' skip RARROWEQUAL <- '>=' skip RBRACE <- '}' skip RBRACKET <- ']' skip RPAREN <- ')' skip SEMICOLON <- ';' skip SLASH <- '/' ![=] skip SLASHEQUAL <- '/=' skip TILDE <- '~' skip end_of_word <- ![a-zA-Z0-9_] skip KEYWORD_align <- 'align' end_of_word KEYWORD_allowzero <- 'allowzero' end_of_word KEYWORD_and <- 'and' end_of_word KEYWORD_anyframe <- 'anyframe' end_of_word KEYWORD_anytype <- 'anytype' end_of_word KEYWORD_asm <- 'asm' end_of_word KEYWORD_async <- 'async' end_of_word KEYWORD_await <- 'await' end_of_word KEYWORD_break <- 'break' end_of_word KEYWORD_callconv <- 'callconv' end_of_word KEYWORD_catch <- 'catch' end_of_word KEYWORD_comptime <- 'comptime' end_of_word KEYWORD_const <- 'const' end_of_word KEYWORD_continue <- 'continue' end_of_word KEYWORD_defer <- 'defer' end_of_word KEYWORD_else <- 'else' end_of_word KEYWORD_enum <- 'enum' end_of_word KEYWORD_errdefer <- 'errdefer' end_of_word KEYWORD_error <- 'error' end_of_word KEYWORD_export <- 'export' end_of_word KEYWORD_extern <- 'extern' end_of_word KEYWORD_fn <- 'fn' end_of_word KEYWORD_for <- 'for' end_of_word KEYWORD_if <- 'if' end_of_word KEYWORD_inline <- 'inline' end_of_word KEYWORD_noalias <- 'noalias' end_of_word KEYWORD_nosuspend <- 'nosuspend' end_of_word KEYWORD_noinline <- 'noinline' end_of_word KEYWORD_opaque <- 'opaque' end_of_word KEYWORD_or <- 'or' end_of_word KEYWORD_orelse <- 'orelse' end_of_word KEYWORD_packed <- 'packed' end_of_word KEYWORD_pub <- 'pub' end_of_word KEYWORD_resume <- 'resume' end_of_word KEYWORD_return <- 'return' end_of_word KEYWORD_linksection <- 'linksection' end_of_word KEYWORD_struct <- 'struct' end_of_word KEYWORD_suspend <- 'suspend' end_of_word KEYWORD_switch <- 'switch' end_of_word KEYWORD_test <- 'test' end_of_word KEYWORD_threadlocal <- 'threadlocal' end_of_word KEYWORD_try <- 'try' end_of_word KEYWORD_union <- 'union' end_of_word KEYWORD_unreachable <- 'unreachable' end_of_word KEYWORD_usingnamespace <- 'usingnamespace' end_of_word KEYWORD_var <- 'var' end_of_word KEYWORD_volatile <- 'volatile' end_of_word KEYWORD_while <- 'while' end_of_word keyword <- KEYWORD_align / KEYWORD_allowzero / KEYWORD_and / KEYWORD_anyframe / KEYWORD_anytype / KEYWORD_asm / KEYWORD_async / KEYWORD_await / KEYWORD_break / KEYWORD_callconv / KEYWORD_catch / KEYWORD_comptime / KEYWORD_const / KEYWORD_continue / KEYWORD_defer / KEYWORD_else / KEYWORD_enum / KEYWORD_errdefer / KEYWORD_error / KEYWORD_export / KEYWORD_extern / KEYWORD_fn / KEYWORD_for / KEYWORD_if / KEYWORD_inline / KEYWORD_noalias / KEYWORD_nosuspend / KEYWORD_noinline / KEYWORD_opaque / KEYWORD_or / KEYWORD_orelse / KEYWORD_packed / KEYWORD_pub / KEYWORD_resume / KEYWORD_return / KEYWORD_linksection / KEYWORD_struct / KEYWORD_suspend / KEYWORD_switch / KEYWORD_test / KEYWORD_threadlocal / KEYWORD_try / KEYWORD_union / KEYWORD_unreachable / KEYWORD_usingnamespace / KEYWORD_var / KEYWORD_volatile / KEYWORD_while {#end_syntax_block#} {#header_close#} {#header_open|Zen#}- Communicate intent precisely.
- Edge cases matter.
- Favor reading code over writing code.
- Only one obvious way to do things.
- Runtime crashes are better than bugs.
- Compile errors are better than runtime crashes.
- Incremental improvements.
- Avoid local maximums.
- Reduce the amount one must remember.
- Focus on code rather than style.
- Resource allocation may fail; resource deallocation must succeed.
- Memory is a resource.
- Together we serve the users.