is a general-purpose programming language and toolchain for maintaining , , and software.
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.
The 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.
Alternatively, the Zig Standard Library documentation is provided with each Zig distribution. It can be rendered via a local webserver with:
Most of the time, it is more appropriate to write to stderr rather than stdout, and whether or not the message is successfully written to the stream is irrelevant. Also, formatted printing often comes in handy. For this common case, there is a simpler API:
In this case, the may be omitted from the return type of because no errors are returned from the function.
See also:
There are three types of comments. Normal comments are ignored, while and are used by the compiler to generate the package documentation.
There are no multiline comments. Zig has the property that each line of code can be tokenized independently.
A doc comment is one that begins with exactly three slashes (i.e. but not ); multiple doc comments in a row are merged together to form a multiline doc comment. The doc comment documents whatever immediately follows it.
Doc comments are only allowed in certain places; it is 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.
Doc comments can be interleaved with normal comments, which are ignored.
A top-level doc comment is one that begins with two slashes and an exclamation point: ; it documents the type which owns the containing .
It is a compile error if a top-level doc comment is not placed at the start of a namespace, before any expressions.
A namespace in Zig is created by , , , and .
They contain , declarations, and blocks.
Although namespaces use curly braces to surround their definition, they should not be confused with or function bodies.
, with the keyword and curly braces omitted.
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 .
If a name that does not fit these requirements is needed, such as for linking with external libraries, the syntax may be used.
In addition to the integer types above, arbitrary bit-width integers can be referenced by using an identifier of or followed by digits. For example, the identifier refers to a signed 7-bit integer. The maximum allowed bit-width of an integer type is .
See also:
See also:
String literals are constant single-item 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 to both and . Dereferencing string literals converts them to .
Because Zig source code is , 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. It is possible to embed non-UTF-8 bytes into a string literal using notation.
Indexing into a string containing non-ASCII bytes returns individual bytes, whether valid UTF-8 or not.
Unicode code point literals have type , the same as . All are valid in both string literals and Unicode code point literals.
See also:
Note that the maximum valid Unicode scalar value is .
Multiline string literals have no escapes and can span across multiple lines. To start a multiline string literal, use the 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 then a newline is appended and the string literal continues.
See also:
Use the keyword to assign a value to an identifier:
applies to all of the bytes that the identifier immediately addresses. have their own const-ness.
If you need a variable that you can modify, use the keyword:
Variables must be initialized:
Use to leave variables uninitialized:
can be to any type. Once this happens, it is no longer possible to detect that the value is . means the value could be anything, even something that is nonsense according to the type. Translated into English, means "Not a meaningful value. Using this value would be a bug. The value will be unused, or overwritten before being used."
In and mode, Zig writes 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.
A destructuring assignment can separate elements of indexable aggregate types (, , ):
A destructuring expression may only appear within a block (i.e. not at scope). The left hand side of the assignment must consist of a comma separated list, each element of which may be either an lvalue (for instance, an existing ) or a variable declaration:
A destructure may be prefixed with the keyword, in which case the entire destructure expression is evaluated at . All s declared would be s and all expressions (both result locations and the assignee expression) are evaluated at .
See also:
Code written within one or more declarations can be used to ensure behavior meets expectations:
The code sample tests the to ensure that it returns given the input . From this test's perspective, the function is said to be .
is a tool that creates and runs a test build. By default, it builds and runs an executable program using the provided by the as its main entry point. During the build, declarations found while 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 command. These lines are printed to standard error by the default test runner:
Test declarations contain the , followed by an optional name written as a or an , followed by a containing any valid Zig code that is allowed in a .
Non-named test blocks always run during test builds and are exempt from .
Test declarations are similar to : they have a return type and a block of code. The implicit return type of is the , and it cannot be changed. When a Zig source file is not built using the 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:
Test declarations named using an identifier are . The identifier must refer to another declaration in scope. A doctest, like a , serves as documentation for the associated declaration, and will appear in the generated documentation for the declaration.
An effective doctest should be self-contained and focused on the declaration being tested, answering questions a new user might have about its interface or intended usage, while avoiding unnecessary or confusing details. A doctest is not a substitute for a doc comment, but rather a supplement and companion providing a testable, code-driven example, verified by .
The default test runner checks for an returned from a test. When a test returns an error, the test is considered a failure and its is output to standard error. The total number of failures will be reported after all tests have run.
One way to skip tests is to filter them out by using the command line parameter . 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 command line parameter.
To programmatically skip a test, make a return the error 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.
When code allocates using the 's testing allocator, , the default test runner will report any leaks that are found from using the testing allocator:
See also:
Use the to detect a test build:
The default test runner and the Zig Standard Library's testing namespace output messages to standard error.
The Zig Standard Library's namespace contains useful functions to help you create tests. In addition to the function, this document uses a couple of more functions as exemplified here:
The Zig Standard Library also contains functions to compare , strings, and more. See the rest of the namespace in the for more available functions.
has a few command line parameters which affect the compilation. See for a full list.
A variable is a unit of storage.
It is generally preferable to use rather than when declaring a variable. This causes less work for both humans and computers to do when reading code, and creates more optimization opportunities.
Variables are never allowed to shadow from an outer scope.
The keyword or builtin function can be used to link against a variable that is exported from another object. The keyword or 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:
level variables have global lifetime and are order-independent and lazily analyzed. The initialization value of namespace level variables is implicitly . If a namespace level variable is then its value is -known, otherwise it is runtime-known.
Namespace level variables may be declared inside a , , , or :
It is also possible to have local variables with global lifetime by using inside functions.
A variable may be specified to be a thread-local variable using the keyword, which makes each thread work with a separate instance of the variable:
For , all thread local variables are treated as regular .
Thread local variables may not be .
Local variables occur inside , blocks, and labeled .
When a local variable is , it means that after initialization, the variable's value will not change. If the initialization value of a variable is -known, then the variable is also -known.
A local variable may be qualified with the keyword. This causes the variable's value to be -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 expression are implicitly variables.
Integer literals have no size limitation, and if any Illegal 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 safety-checked .
In this function, values and are known only at runtime, and thus this division operation is vulnerable to both and .
Operators such as and cause on integer overflow. Alternative operators are provided for wrapping and saturating arithmetic on all targets. and perform wrapping arithmetic while and perform saturating arithmetic.
Zig supports arbitrary bit-width integers, referenced by using an identifier of or followed by digits. For example, the identifier refers to a signed 7-bit integer. The maximum allowed bit-width of an integer type is . For signed integer types, Zig uses a representation.
See also:
Zig has the following floating point types:
Float literals have type which is guaranteed to have the same precision and operations of the largest other floating point type, which is .
Float literals to any floating point type, and to any type when there is no fractional component.
There is no syntax for NaN, infinity, or negative infinity. For these special values, one must use the standard library:
By default floating point operations use mode, but you can switch to mode on a per-block basis:
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.
See also:
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.
Zig features partial operator precedence: not every operator has a defined precedence with every other operator. Mixing operators with ambiguous precedence is prohibited and parentheses are mandatory. Consequently, valid code is typically auto-descriptive; when reading and writing Zig code, there are very few precedence rules you'll need to remember.
There is a set of operators (prefix operators, suffix operators, etc) that have unambiguously higher precedence than all other operators. That set of operators has the following precedence table:
For the other operators, simplified operator precedence tables are provided below, each containing only the information that you'll need to know when reading/writing code that uses that particular category of operators. The operators that have ambiguous precedence or semantic errors with the relevant operators have been omitted, as have the operators with higher precedence (those shown above).
For arithmetic operators:
For bitwise operators:
For null and error recovery operators:
For error set operators:
For array concatenation operators:
The full precedence rules can be found in the , which also includes an .
See also:
Multidimensional arrays can be created by nesting arrays:
The syntax describes an array which has a sentinel element of value at the index corresponding to the length .
See also:
Arrays can be destructured:
See also:
A vector is a group of booleans, , , or which are operated on in parallel, using SIMD instructions if possible. Vector types are created with the builtin function .
Vectors generally support the same builtin operators as their underlying base types. The only exception to this is the keywords and on vectors of bools, since these operators affect control flow, which is not allowed for vectors. All other operations are performed element-wise, and return a vector of the same length as the input vectors. This includes:
It is prohibited to use a math operator on a mixture of scalars (individual numbers) and vectors. Zig provides the builtin to easily convert from scalars to vectors, and it supports 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 and 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.
TODO talk about C ABI interop TODO consider suggesting std.MultiArrayList
See also:
Vectors and each have a well-defined and therefore support between each other. implicitly peforms .
Arrays have well-defined byte layout, but vectors do not, making between them .
Vectors can be destructured:
See also:
Zig has two kinds of pointers: single-item and many-item.
These types are closely related to and :
Use to obtain a single-item pointer:
Zig supports pointer arithmetic. It's better to assign the pointer to and increment that variable. For example, directly incrementing the pointer from a slice will corrupt it.
In Zig, we generally prefer rather than . 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 Illegal Behavior. This is one reason we prefer slices to pointers.
Pointers work at compile-time too, as long as the code does not depend on an undefined memory layout:
To convert an integer address into a pointer, use . To convert a pointer to an integer, use :
Zig is able to preserve memory addresses in comptime code, as long as the pointer is never dereferenced:
converts a pointer's element type to another. This creates a new pointer that can cause undetectable Illegal Behavior depending on the loads and stores that pass through it. Generally, other kinds of type conversions are preferable to if possible.
See also:
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 . In the following code, loads and stores with are guaranteed to all happen and in the same order as in source code:
Note that is unrelated to concurrency and . If you see code that is using for something other than Memory Mapped Input/Output, it is probably a bug.
Each type has an - 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 to find out this value for any type.
Alignment depends on the CPU architecture, but is always a power of two, and less than .
Pointer types may explicitly specify an alignment in bytes. If it is not specified, the alignment is assumed to be equal to the alignment of the underlying type.
In the same way that a can be to a , 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:
If you have a pointer or a slice that has a small alignment, but you know that it actually has a bigger alignment, use to change the pointer into a more aligned pointer. This is a no-op at runtime, but inserts a :
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 instead. with are not the same size as pointers. In this code example, if the pointer did not have the attribute, this would be a panic:
The syntax describes a pointer that has a length determined by a sentinel value. This provides protection against buffer overflow and overreads.
See also:
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 field.
This is one reason we prefer slices to pointers.
See also:
Even though Zig only has syntax for slicing based on start and end indices, by slicing twice, one can express a operation.
The pattern is always better expressed because:
The syntax 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 index.
Sentinel-terminated slices can also be created using a variation of the slice syntax , where is a many-item pointer, array or slice and is the sentinel value.
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-checked results.
See also:
Each struct field may have an expression indicating the default field value. Such expressions are executed at , and allow the field to be omitted in a struct literal expression:
Default field values are only appropriate when the data invariants of a struct cannot be violated by omitting that field from an initialization.
For example, here is an inappropriate use of default struct field initialization:
Above you can see the danger of ignoring this principle. The default field values caused the data invariant to be violated, causing illegal behavior.
To fix this, remove the default values from all the struct fields, and provide a named default value:
If a struct value requires a runtime-known value in order to be initialized without violating data invariants, then use an initialization method that accepts those runtime values, and populates the remaining fields.
An has in-memory layout matching the C ABI for the target.
If well-defined in-memory layout is not required, is a better choice because it places fewer restrictions on the compiler.
See for a struct that has the ABI of its backing integer, which can be useful for modeling flags.
See also:
structs, like , are based on the concept of interpreting integers differently. All packed structs have a , which is implicitly determined by the total bit count of fields, or explicitly specified. Packed structs have well-defined memory layout - exactly the same ABI as their backing integer.
Each field of a packed struct is interpreted as a logical sequence of bits, arranged from least to most significant. Allowed field types:
This means that a can participate in a or a to reinterpret memory. This even works at :
The backing integer can be inferred or explicitly provided. When inferred, it will be unsigned. When explicitly provided, its bit width will be enforced at compile time to exactly match the total bit width of the fields:
A can be converted to and from its backing integer using and :
Zig allows the address to be taken of a non-byte-aligned field:
However, the pointer to a non-byte-aligned field has special properties and cannot be passed when a normal pointer is expected:
In this case, the function 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:
This can be observed with and :
Packed structs have the same alignment as their backing integer, however, overaligned pointers to packed structs can override this:
It's also possible to set alignment of struct fields:
Equating packed structs results in a comparison of the backing integer, and only works for the and .
Field access and assignment can be understood as shorthand for bitshifts on the backing integer. These operations are not , so beware using field access syntax when combined with memory-mapped input-output (MMIO). Instead of field access on , construct a fully-formed new value first, then write that value to the volatile pointer.
Since all structs are anonymous, Zig infers the type name based on a few rules.
Zig allows omitting the struct type of a literal. When the result is , the struct literal will directly instantiate the , with no copy:
The struct type can be inferred. Here the does not include a type, and so Zig infers the type:
Anonymous structs can be created without specifying field names, and are referred to as "tuples". An empty tuple looks like and can be seen in one of the .
The fields are implicitly named using numbers starting from 0. Because their names are integers, they cannot be accessed with syntax without also wrapping them in . Names inside are always recognised as .
Like arrays, tuples have a .len field, can be indexed (provided the index is comptime-known) and work with the ++ operator. They can also be iterated over with .
Tuples can be .
Tuple destructuring is helpful for returning multiple values from a block:
Tuple destructuring is helpful for dealing with functions and built-ins that return multiple values as a tuple:
See also:
See also:
See also:
By default, enums are not guaranteed to be compatible with the C ABI:
For a C-ABI-compatible enum, provide an explicit tag type to the enum:
Enum literals allow specifying the name of an enum field without specifying the enum type:
A non-exhaustive enum can be created by adding a trailing field. The enum must specify a tag type and cannot consume every enumeration value.
on a non-exhaustive enum always results in a valid enum value.
A switch on a non-exhaustive enum can include a prong as an alternative to an prong. With a prong the compiler errors if all the known tag names are not handled by the switch.
A bare 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 , or use an or a which have guaranteed in-memory layout. is safety-checked :
You can activate another field by assigning the entire union:
In order to use with a union, it must be a or a .
To initialize a union when the tag is a -known name, see .
Unions can be declared with an enum tag type. This turns the union into a union, which makes it eligible to use with expressions. When switching on tagged unions, the tag value can be obtained using an additional capture. Tagged unions coerce to their tag type: .
In order to modify the payload of a tagged union in a switch expression, place a before the variable name to make it a pointer:
Unions can be made to infer the enum tag type. Further, unions can have methods just like structs and enums.
Unions with inferred enum tag types can also assign ordinal values to their inferred tag. This requires the tag to specify an explicit integer type. can be used to access the ordinal value corresponding to the active field.
can be used to return a value representing the field name:
An has memory layout guaranteed to be compatible with the target C ABI.
See also:
A has well-defined in-memory layout and is eligible to be in a .
All fields in a packed union must have the same .
Equating packed unions results in a comparison of the backing integer, and only works for the and .
See also:
syntax can be used to initialize unions without specifying the type:
declares a new type with an unknown (but non-zero) size and alignment. It can contain declarations the same as , , and .
This is typically used for type safety when interacting with C code that does not expose struct details. Example:
Blocks are used to limit the scope of variable declarations:
Blocks are expressions. When labeled, can be used to return a value from the block:
Here, can be any name.
See also:
are never allowed to "hide" other identifiers by using the same name:
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:
An empty block returns the single value of type :
can be used to capture the field values of a . Modifications to the field values can be done by placing a before the capture variable name, turning it into a pointer.
See also:
When a expression does not have an clause, it must exhaustively list all the possible values. Failure to do so is a compile error:
can be useful to use with to avoid repetitively specifying or types:
When switching on errors, some special cases are allowed to simplify generic programming patterns:
When a switch statement is labeled, it can be referenced from a or . will return a value from the .
A targeting a switch must have an operand. When executed, it will jump to the matching prong, as if the were executed again with the 's operand replacing the initial switch value.
Semantically, this is equivalent to the following loop:
This can improve clarity of (for example) state machines, where the syntax is unambiguous, explicit, and immediately understandable.
However, the motivating example is a switch on each element of an array, where using a single switch can improve clarity and performance:
If the operand to is -known, then it can be lowered to an unconditional branch to the relevant case. Such a branch is perfectly predicted, and hence typically very fast to execute.
If the operand is runtime-known, each can embed a conditional branch inline (ideally through a jump table), which allows a CPU to predict its target independently of any other prong. A loop-based lowering would force every branch through the same dispatch point, hindering branch prediction.
Switch prongs can be marked as to generate the prong's body for each possible value it could have, making the captured value .
The keyword may also be combined with ranges:
prongs can be used as a type safe alternative to loops:
When using an inline prong switching on an union an additional capture can be used to obtain the union's enum tag value at comptime, even though its payload might only be known at runtime.
See also:
A while loop is used to repeatedly execute an expression until some condition is no longer true.
Use to exit a while loop early.
Use to jump back to the beginning of the loop.
While loops support a continue expression which is executed when the loop is continued. The keyword respects this expression.
While loops are expressions. The result of the expression is the result of the clause of a while loop, which is executed when the condition of the while loop is tested as false.
, like , accepts a value parameter. This is the result of the expression. When you from a while loop, the branch is not evaluated.
When a loop is labeled, it can be referenced from a or from within a nested loop:
Just like expressions, while loops can take an optional as the condition and capture the payload. When is encountered the loop exits.
When the syntax is present on a expression, the while condition must have an .
The branch is allowed on optional iteration. In this case, it will be executed on the first null value encountered.
Just like 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 is present on a expression, the while condition must have an .
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.
It is recommended to use loops only for one of these reasons:
See also:
When a loop is labeled, it can be referenced from a or from within a nested loop:
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.
It is recommended to use loops only for one of these reasons:
See also:
See also:
Executes an expression unconditionally at scope exit.
Defer expressions are evaluated in reverse order.
Inside a defer expression the return statement is not allowed.
See also:
In and mode emits a call to with the message .
In and mode, the optimizer uses the assumption that code will never be hit to perform optimizations.
In fact, this is how is implemented:
See also:
is the type of:
When resolving types together, such as clauses or prongs, the type is compatible with every other type. Consider:
Another use case for is the function:
There is a difference between a function and a function . Function bodies are -only types while function may be runtime-known.
Primitive types such as and 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.
For extern functions, Zig follows the C ABI for passing structs and unions by value.
Function parameters can be declared with in place of the type. In this case the parameter types will be inferred when the function is called. Use and to get information about the inferred type.
Adding the keyword to a function definition makes that function become at the callsite. to be possibly observed by optimization passes, but has implications on the types and values involved in the function call.
Unlike normal function calls, arguments at an inline function callsite which are compile-time known are treated as . This can potentially propagate all the way to the return value:
If is removed, the test fails with the compile error instead of passing.
Use of what the compiler is allowed to do. In exchange, these use cases are addressed:
For an alternative to that merely hints to the compiler that inlining a function may be valuable, use .
An error set is like an . 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 error set type defaults to a , though if the maximum number of distinct error values is provided via the command line parameter an integer type with the minimum number of bits required to represent all of the error values will be used.
You can an error from a subset to a superset:
But you cannot an error from a superset to a subset:
There is a shortcut for declaring an error set with only 1 value, and then getting that value:
This is equivalent to:
This becomes useful when using .
refers to the global error set. This is the error set that contains all errors in the entire compilation unit, i.e. it is the union of all other error sets.
You can 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 .
An error set type and normal type can be combined with the 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:
Notice the return type is . 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 , 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 . Both types to .
What it looks like to use this function varies depending on what you're trying to do. One of the following:
If you want to provide a default value, you can use the binary operator:
In this code, will be equal to the successfully parsed string, or a default value of 13. The type of the right hand side of the binary operator must match the unwrapped error union type, or be of type .
If you want to provide a default value with after performing some logic, you can combine with named :
Let's say you wanted to return the error if you got one, otherwise continue with the function logic:
There is a shortcut for this. The expression:
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.
Maybe you know with complete certainty that an expression will never be an error. In this case you can do this:
number = parseU64(, ) ;
Here we know for sure that "1234" will parse successfully. So we put the value on the right hand side. invokes safety-checked , so in and , triggers a safety panic by default. So, while we're debugging the application, if there a surprise error here, the application would crash appropriately.
You may want to take a different action for every situation. For that, we combine the and expression:
Finally, you may want to handle only some errors. For that, you can capture the unhandled errors in the case, which now contains a narrower error set:
You must use the variable capture syntax. If you don't need the variable, you can capture with and avoid the .
The other component to error handling is defer statements. In addition to an unconditional , Zig has , which evaluates the deferred expression on block exit path if and only if the function returned with an error from the block.
Example:
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.
A couple of other tidbits about error handling:
See also:
An error union is created with the binary operator. You can use compile-time reflection to access the child type of an error union:
Use the 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 is .
This is especially useful for functions which return different error sets depending on branches. For example, the Zig standard library uses for the error set of opening files.
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 operator to the function’s return type, like :
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.
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 everywhere and then still be able to know what happened if an error ends up bubbling all the way out of your application.
Look closely at this example. This is no stack trace.
You can see that the final error bubbled up was , but the original error that started this whole thing was . In the 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:
Here, the stack trace does not explain how the control flow in got to the 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 builds and disabled by default in , and builds.
There are a few ways to activate this error return tracing feature:
To analyze performance cost, there are two cases:
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 calls a function returning . This is to initialize this struct in the stack memory:
Here, N is the maximum function call depth as determined by call graph analysis. Recursion is ignored and counts for 2.
A pointer to 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 statement (only for the statements that return errors), Zig generates a call to this function:
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 to make the call to 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.
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:
Now the variable could be an , or .
Instead of integers, let's talk about pointers. Null references are the source of many runtime exceptions, and even stand accused of being .
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
Zig code
Here, Zig is at least as convenient, if not more, than C. And, the type of "ptr" is . The keyword unwrapped the optional type and therefore 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:
In Zig you can accomplish the same thing:
Once again, the notable thing here is that inside the if block, 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 - in . The optimizer can sometimes make better decisions knowing that pointer arguments cannot be null.
An optional is created by putting in front of a type. You can use compile-time reflection to access the child type of an optional:
Just like , has its own type, and the only way to use it is to cast it to a different type:
An optional pointer is guaranteed to be the same size as a pointer. The of the optional is guaranteed to be address 0.
See also:
A converts a value of one type to another. Zig has for conversions that are known to be completely safe and unambiguous, and for conversions that one would not want to happen on accident. There is also a third kind of type conversion called for the case when a result type must be decided given multiple operand types.
Type coercion occurs when one type is expected, but different type is provided:
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 .
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:
These casts are no-ops at runtime since the value representation does not change.
In addition, pointers coerce to const optional pointers:
coerce to integer types which can represent every value of the old type, and likewise coerce to float types which can represent every value of the old type.
coerce to if every possible integer value can be stored in the float without rounding (i.e. the integer's precision does not exceed the float's significand precision). Larger integer types that cannot be safely coerced must be explicitly casted with .
A compiler error is appropriate because this ambiguous expression leaves the compiler two choices about the coercion.
See also:
The payload type of , as well as , coerce to the optional type.
Optionals work nested inside the , too:
The payload type of an as well as the coerce to the error union type:
When a number is -known to be representable in the destination type, it may be coerced:
Tagged unions can be coerced to enums, and enums can be coerced to tagged unions when they are -known to be a field of the union that has only one possible value, such as :
See also:
can be coerced to any type.
can be coerced to arrays, if all of the fields have the same type.
Explicit casts are performed via .
Some explicit casts can violate type safety when used incorrectly.
Some explicit casts perform language-level assertions.
Some explicit casts are no-ops at runtime.
Peer Type Resolution occurs in these places:
This kind of type resolution chooses a type that all peer types can coerce into. Here are some examples:
For some types, is 0:
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:
When this turns into machine code, there is no code generated in the body of , even in mode. For example, on x86_64:
These assembly instructions do not have any code associated with the void values - they only perform the function call prologue and epilogue.
can be useful for instantiating generic types. For example, given a , one can pass for the type to make it into a :
Note that this is different from using a dummy value for the hash map value. By using 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.
is distinct from . has a known size of 0 bytes, and has an unknown, but non-zero, size.
Expressions of type are the only ones whose value can be ignored. For example, ignoring a non- expression is a compile error:
However, if the expression has type , there will be no error. Expression results can be explicitly ignored by assigning them to .
During compilation, every Zig expression and sub-expression is assigned optional result location information. This information dictates what type the expression should have (its result type), and where the resulting value should be placed in memory (its result location). The information is optional in the sense that not every expression has this information: assignment to , for instance, does not provide any information about the type of an expression, nor does it provide a concrete memory location to place it in.
As a motivating example, consider the statement . The type annotation here provides a result type of to the initialization expression , instructing the compiler to coerce this integer (initially of type ) to this type. We will see more examples shortly.
This is not an implementation detail: the logic outlined above is codified into the Zig language specification, and is the primary mechanism of type inference in the language. This system is collectively referred to as "Result Location Semantics".
Result types are propagated recursively through expressions where possible. For instance, if the expression has result type , then is given a result type of , allowing the language to perform this coercion before taking a reference.
The result type mechanism is utilized by casting builtins such as . Rather than taking as an argument the type to cast to, these builtins use their result type to determine this information. The result type is often known from context; where it is not, the builtin can be used to explicitly provide a result type.
We can break down the result types for each component of a simple expression as follows:
This result type information is useful for the aforementioned cast builtins, as well as to avoid the construction of pre-coercion values, and to avoid the need for explicit type coercions in some cases. The following table details how some common expressions propagate result types, where and are arbitrary sub-expressions.
In addition to result type information, every expression may be optionally assigned a result location: a pointer to which the value must be directly written. This system can be used to prevent intermediate copies when initializing data structures, which can be important for types which must have a fixed memory address ("pinned" types).
When compiling the simple assignment expression , many languages would create the temporary value on the stack, and then assign it to , potentially performing a type coercion in the process. Zig approaches this differently. The expression is given a result type matching the type of , and a result location of . For many syntactic forms of , this has no practical impact. However, it can have important semantic effects when working with more complex syntax forms.
For instance, if the expression has a result location of , then is given a result location of , and a result location of . Without this system, this expression would construct a temporary struct value entirely on the stack, and only then copy it to the destination address. In essence, Zig desugars the assignment to the two statements .
This can sometimes be important when assigning an aggregate value where the initialization expression depends on the previous value of the aggregate. The easiest way to demonstrate this is by attempting to swap fields of a struct or array - the following logic looks sound, but in fact is not:
The following table details how some common expressions propagate result locations, where and are arbitrary sub-expressions. Note that some expressions cannot provide meaningful result locations to sub-expressions, even if they themselves have a result location.
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.
Compile-time parameters is how Zig implements generics. It is compile-time duck typing.
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 , which is why the parameter in the above snippet must be marked with .
A parameter means that:
For example, if we were to introduce another function to the above snippet:
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 .
For example:
On the flip side, inside the function definition with the 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:
This works because Zig implicitly inlines 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 in this situation looks like this:
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 expressions - they are implicitly inlined when the target expression is compile-time known.
In Zig, the programmer can label variables as . 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 loops allows us to write a function which is partially evaluated at compile-time and partially at run-time.
For example:
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 is generated three different times, for the different values of provided:
Note that this happens even in a debug build. This is not a way to write more optimized code, but it is a way to make sure that what happen at compile-time, happen at compile-time. This catches more errors and allows expressiveness that in other languages requires using macros, generated code, or a preprocessor to accomplish.
In Zig, it matters whether a given expression is known at compile-time or run-time. A programmer can use a 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:
It doesn't make sense that a program could call (or any other external function) at compile-time, so this is a compile error. However, a expression does much more than sometimes cause a compile error.
Within a expression:
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:
Imagine if we had forgotten the base case of the recursive function and tried to run the tests:
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 , which is always a compile error if the compiler knows it happened. But what would have happened if we used a signed integer?
The compiler is supposed to notice that evaluating this function at compile-time took more than 1000 branches, and thus emits an error and gives up. If the programmer wants to increase the budget for compile-time computation, they can use a built-in function called to change the default number 1000 to something else.
However, there is a causing it to stack overflow instead of having the proper behavior here. I'm terribly sorry about that. I hope to get this resolved before the next release.
What if we fix the base case, but put the wrong value in the line?
At level (outside of any function), all expressions are implicitly expressions. This means that we can use functions to initialize complex constant data. For example:
When we compile this program, Zig generates the constants with the answer pre-computed. Here are the lines from the generated LLVM IR:
Note that we did not have to do anything special with the syntax of these functions. For example, we could call the function as is with a slice of numbers whose length and values were only known at run-time.
Zig uses comptime capabilities to implement generic data structures without introducing any special-case syntax.
Here is an example of a generic data structure.
That's it. It's a function that returns an anonymous . For the purposes of error messages and debugging, Zig infers the name 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.
In this example, the 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, refers to itself as a pointer, which has a well-defined size at compile time, so it works fine.
Putting all of this together, let's see how works in Zig.
Let's crack open the implementation of this and see how it works:
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:
is a function that takes a parameter of any type, and does different things depending on the type:
And now, what happens if we give too many arguments to ?
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 :
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.
See also:
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:
Dissecting the syntax:
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.
Output constraints are still considered to be unstable in Zig, and so and must be used to understand the semantics.
Note that some breaking changes to output constraints are planned with .
Input constraints are still considered to be unstable in Zig, and so and must be used to understand the semantics.
Note that some breaking changes to input constraints are planned with .
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 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 .
When an assembly expression occurs in a level block, this is .
This kind of assembly has different rules than inline assembly. First, 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: @atomic rmw
TODO: builtin atomic memory ordering enum
See also:
Async functions regressed with the release of 0.11.0. The current plan is to reintroduce them as a lower level primitive that powers I/O implementations.
Tracking issue:
Builtin functions are provided by the compiler and are prefixed with . The keyword on a parameter means that the parameter must be known at compile time.
Converts a pointer from one address space to another. The new address space is inferred based on the result type. 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.
Performs and returns a tuple with the result and a possible overflow bit.
can be , , or . Changes the alignment of a pointer. The alignment to use is inferred based on the result type.
A is added to the generated code to make sure the pointer is aligned as promised.
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.
The result is a target-specific compile time constant. It is guaranteed to be less than or equal to .
See also:
Performs . This cast is allowed when the conversion is unambiguous and safe, and is the preferred way to convert between types, whenever possible.
This builtin function atomically dereferences a pointer to a and returns the value.
must be a pointer, a , a float, an integer, an enum, or a packed struct.
can be found with .
See also:
This builtin function dereferences a pointer to a and atomically modifies the value and returns the previous value.
must be a pointer, a , a float, an integer, an enum, or a packed struct.
can be found with .
can be found with .
See also:
This builtin function dereferences a pointer to a and atomically stores the given value.
must be a pointer, a , a float, an integer, an enum, or a packed struct.
can be found with .
See also:
Converts an , a or a value to its backing integer.
Also works with , acting on the active enum tag value.
See also:
Converts a value of one type to another type. The return type is the inferred result type.
Asserts that .
Asserts that . Use or if you need this.
Can be used for these things for example:
Works at compile-time if 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 (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.
Attempting to convert an integer with no corresponding tag value to an invokes safety-checked .
See also:
Returns the bit offset of a field relative to its containing struct.
For non , this will always be divisible by . For packed structs, non-byte-aligned fields will share a byte offset, but they will have different bit offsets.
See also:
This function returns the number of bits it takes to store 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 and , the result is .
See also:
Hints to the optimizer how likely a given branch of control flow is to be reached.
can be found with .
This function is only valid as the first statement in a control flow branch, or the first statement in a function.
This function inserts a platform-specific debug trap instruction which causes debuggers to break there. Unlike for , execution may continue after this point if the program is resumed.
This function is only valid within function scope.
See also:
Fused multiply-add, similar to , except only rounds once, and is thus more accurate.
Supports and of floats.
must be an integer type or an integer vector type with bit count evenly divisible by 8.
may be an or .
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 bytes. This is demonstrated with . , which means that a 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 is specified to be , then only 3 bytes are reversed.
accepts any integer type or integer vector type.
Reverses the bitpattern of an integer value, including the sign bit if applicable.
For example 0b10110110 (, ) becomes 0b01101101 (, ).
Returns the byte offset of a field relative to its containing struct.
See also:
Calls a function, in the same way that invoking an expression with parentheses does:
allows more flexibility than normal function call syntax does. The enum is reproduced here:
must be an integer type or an integer vector type.
may be an or .
Counts the number of most-significant (leading in a big-endian sense) zeroes in an integer - "count leading zeroes".
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 is zero, returns the bit width of integer type .
See also:
This function performs a strong atomic compare-and-exchange operation, returning if the current value is the given expected value. It's the equivalent of this code, except atomic:
If you are using cmpxchg in a retry loop, is the better choice, because it can be implemented more efficiently in machine instructions.
must be a pointer, a , an integer, an enum, or a packed struct.
must be
can be found with .
See also:
This function performs a weak atomic compare-and-exchange operation, returning if the current value is the given expected value. It's the equivalent of this code, except atomic:
If you are using cmpxchg in a retry loop, the sporadic failure will be no problem, and is the better choice, because it can be implemented more efficiently in machine instructions. However if you need a stronger guarantee, use .
must be a pointer, a , an integer, an enum, or a packed struct.
must be
can be found with .
See also:
This function, when semantically analyzed, causes a compile error with the message .
There are several ways that code avoids being semantically checked, such as using or with compile time constants, and functions.
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.
Remove qualifier from a pointer.
must be an integer type or an integer vector type.
may be an or .
Counts the number of least-significant (trailing in a big-endian sense) zeroes in an integer - "count trailing zeroes".
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 is zero, returns the bit width of integer type .
See also:
Implements the C macro .
See also:
Implements the C macro .
See also:
Implements the C macro .
See also:
Implements the C macro . Only valid inside a variadic function.
See also:
Exact division. Caller guarantees and .
For a function that returns a possible error code, use .
See also:
Floored division. Rounds toward negative infinity. For unsigned integers it is the same as . Caller guarantees and .
For a function that returns a possible error code, use .
See also:
Truncated division. Rounds toward zero. For unsigned integers it is the same as . Caller guarantees and .
For a function that returns a possible error code, use .
See also:
Ceiled division. Rounds toward positive infinity. Caller guarantees and .
For a function that returns a possible error code, use .
See also:
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 . The contents of the array are the contents of the file. This is equivalent to a with the file contents.
is absolute or relative to the current file, just like .
See also:
Deprecated. Use or instead.
Converts an integer into an value. The return type is the inferred result type.
Attempting to convert an integer with no corresponding value in the enum invokes safety-checked . Note that a has corresponding values for all integers in the enum's integer tag type: the value represents all the remaining unnamed integers in the enum's tag type.
See also:
Converts from the integer representation of an error into 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-checked .
See also:
This function returns the string representation of an error. The string representation of is .
If there are no calls to in an entire application, or all calls have a compile-time known value for , then no error name table will be generated.
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 .
Converts an error set or error union value from one error set to another error set. The return type is the inferred result type. Attempting to convert an error which is not in the destination error set results in safety-checked .
Creates a symbol in the output object file which refers to the target of .
must point to a global variable or a comptime-known constant.
This builtin can be called from a block to conditionally export symbols. When points to a function with the C calling convention and is , this is equivalent to the keyword used on a function:
This is equivalent to:
Note that even when using , the syntax for can be used to choose any string for the symbol name:
When looking at the resulting object, you can see the symbol is used verbatim:
See also:
Creates a reference to an external symbol in the output object file. T must be a pointer type.
See also:
Performs field access by a compile-time string. Works on both fields and declarations.
Given a pointer to a struct or union field, returns a pointer to the struct or union containing that field. The return type (pointer to the parent struct or union in question) is the inferred result type.
If does not point to the field of an instance of the result type, and the result type has ill-defined layout, invokes unchecked .
Given a type and the name of one of its fields, returns the type of that field.
Convert from one float type to another. This cast is safe, but may cause the numeric value to lose precision. The return type is the inferred result type.
Converts an integer to the closest floating point representation. The return type is the inferred result type. To convert the other way, use , , , or . This operation is legal for all values of all integer types.
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.
Converts an integer into a , a or a value. The return type is the inferred result type.
Attempting to convert an integer with no corresponding tag value to an invokes safety-checked . Note that a has corresponding values for all integers in the enum's integer tag type: the value represents all the remaining unnamed integers in the enum's tag type.
See also:
Returns whether or not a has a public declaration matching .
Caution: using to implement conditional compilation based on the presence or absence of declarations in an API runs the risk of introducing dead code into the codebase, unnoticed. For example, if the field is ever renamed, code which uses will compile successfully while failing to enable or disable an intended block of code. Even a simple typo in the field name passed to would go unnoticed by the compiler. Thus, it is safer to use alternative methods to check for the presence or absence of a particular declaration where possible. For example, if the target operating system would indicate whether a particular function is available, it is more maintainable to check rather than .
See also:
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:
Imports the file at , adding it to the compilation if it is not already added. is either a relative path to another file from the file containing the call, or it is the name of a , with the import referring to the root source file of that module. Either way, the file path must end in either (for a Zig source file) or (for a ZON data file).
If refers to a Zig source file, then returns that file's , essentially as if the builtin call was replaced by . The return type is .
If refers to a ZON file, then returns the value of the literal in the file. If there is an inferred , then the return type is that type, and the ZON literal is interpreted as that type ( are propagated through the ZON expression). Otherwise, the return type is the type of the equivalent Zig expression, essentially as if the builtin call was replaced by the ZON file contents.
The following modules are always available for import:
See also:
Returns whether the builtin was run in a context. The result is a compile-time constant.
This can be used to provide alternative, comptime-friendly implementations of functions. It should not be used, for instance, to exclude certain functions from being evaluated at comptime.
See also:
Converts an integer to another integer while keeping the same numerical value. The return type is the inferred result type. Attempting to convert a number which is out of range of the destination type results in safety-checked .
To truncate the significant bits of a number out of range of the destination type, use .
If is , then this is semantically equivalent to .
Converts to and to .
Deprecated. Use or instead.
Converts an enumeration value into its integer tag type. When a tagged union is passed, the tag value is used as the enumeration value.
See also:
Supports the following types:
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:
Deprecated. Equivalent to .
See also:
Converts to a which is the address of the pointer. can be or .
See also:
Takes two or more arguments and returns the biggest value included (the maximum). This builtin accepts integers, floats, and vectors of either. In the latter case, the operation is performed element wise.
NaNs are handled as follows: return the biggest non-NaN value included. If all operands are NaN, return NaN.
See also:
This function copies bytes from one region of memory to another.
must be a mutable slice, a mutable pointer to an array, or a mutable many-item . It may have any alignment, and it may have any element type.
must be a slice, a pointer to an array, or a many-item . It may have any alignment, and it may have any element type.
The element type must have the same in-memory representation as the element type.
Similar to loops, at least one of and must provide a length, and if two lengths are provided, they must be equal.
Finally, the two memory regions must not overlap.
This function sets all the elements of a memory region to .
must be a mutable slice or a mutable pointer to an array. It may have any alignment, and it may have any element type.
is coerced to the element type of .
For securely zeroing out sensitive contents from memory, you should use
This function copies bytes from one region of memory to another, but unlike the regions may overlap.
must be a mutable slice, a mutable pointer to an array, or a mutable many-item . It may have any alignment, and it may have any element type.
must be a slice, a pointer to an array, or a many-item . It may have any alignment, and it may have any element type.
The element type must have the same in-memory representation as the element type.
Similar to loops, at least one of and must provide a length, and if two lengths are provided, they must be equal.
Takes two or more arguments and returns the smallest value included (the minimum). This builtin accepts integers, floats, and vectors of either. In the latter case, the operation is performed element wise.
NaNs are handled as follows: return the smallest non-NaN value included. If all operands are NaN, return NaN.
See also:
This function returns the size of the Wasm memory identified by 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 .
See also:
This function increases the size of the Wasm memory identified by by 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 .
See also:
Modulus division. For unsigned integers this is the same as . Caller guarantees , otherwise the operation will result in a when runtime safety checks are enabled.
For a function that returns an error code, see .
See also:
Performs and returns a tuple with the result and a possible overflow bit.
Invokes the panic handler function. By default the panic handler function calls the public function exposed in the root source file, or if there is not one specified, the function from .
Generally it is better to use . However, can be useful for 2 scenarios:
See also:
must be an integer type.
may be an or .
Counts the number of bits set in an integer - "population count".
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:
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 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.
can be found with .
Converts a pointer of one type to a pointer of another type. The return type is the inferred result type.
are allowed. Casting an optional pointer which is to a non-optional pointer invokes safety-checked .
cannot be used for:
Converts an integer to a . The return type is the inferred result type. To convert the other way, use . Casting an address of 0 to a destination type which in not and does not have the attribute will result in a panic when runtime safety checks are enabled.
If the destination pointer type does not allow address zero and is zero, this invokes safety-checked .
See also:
Remainder division. For unsigned integers this is the same as . Caller guarantees , otherwise the operation will result in a when runtime safety checks are enabled.
For a function that returns an error code, see .
See also:
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.
Selects values element-wise from or based on . If is , the corresponding element in the result will be and otherwise .
See also:
Increase the maximum number of backwards branches that compile-time code execution can use before giving up and making a compile error.
If the is smaller than the default quota () or a previously explicitly set quota, it is ignored.
Example:
Now we use :
See also:
Changes the current scope's rules about how floating point operations are defined.
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.
can be found with .
See also:
Sets whether runtime safety checks are enabled for the scope that contains the function call.
Note: it is to replace with
Performs the left shift operation (). For unsigned integers, the result is if any 1 bits are shifted out. For signed integers, the result is if any bits that disagree with the resultant sign bit are shifted out.
The type of is an unsigned integer with bits. This is because triggers safety-checked .
is modeled as an integer with an infinite number of bits, meaning that in such case, always produces a result and cannot produce a compile error.
See also:
Performs and returns a tuple with the result and a possible overflow bit.
The type of is an unsigned integer with bits. This is because triggers safety-checked .
See also:
Performs the right shift operation (). Caller guarantees that the shift will not shift any 1 bits out.
The type of is an unsigned integer with bits. This is because triggers safety-checked .
See also:
Constructs a new by selecting elements from and based on .
Each element in selects an element from either or . Positive numbers select from starting at 0. Negative values select from , starting at and going down. It is recommended to use the operator for indexes from so that both indexes can start from (i.e. is ).
For each element of , if it or the selected value from or is , then the resulting element is .
and may differ in length. Out-of-bounds element indexes in result in compile errors.
If or is , it is equivalent to a vector of all with the same length as the other vector. If both vectors are , returns a vector with all elements .
must be an , , , or . The mask may be any vector length, and its length determines the result length.
See also:
This function returns the number of bytes it takes to store 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, the padding would be the offset in bytes between element at index 0 and the element at index 1. For , consider whether you want to use or .
This function measures the size at runtime. For types that are disallowed at runtime, such as and , the result is .
See also:
Produces an array or vector where each element is the value . The return type, including the number of elements, is inferred.
See also:
Transforms a into a scalar value (of type ) by performing a sequential horizontal reduction of its elements using the specified operator .
Not every operator is available for every vector element type:
Note that and reductions on integral types are wrapping; when applied on floating point types the operation associativity is preserved, unless the float mode is set to .
See also:
Returns a struct representing the function's name and location in the source code. This must be called in a function.
Performs the square root of a floating point number. Uses a dedicated hardware instruction when available.
Supports and of floats.
Sine trigonometric function on a floating point number in radians. Uses a dedicated hardware instruction when available.
Supports and of floats.
Cosine trigonometric function on a floating point number in radians. Uses a dedicated hardware instruction when available.
Supports and of floats.
Tangent trigonometric function on a floating point number in radians. Uses a dedicated hardware instruction when available.
Supports and of floats.
Base-e exponential function on a floating point number. Uses a dedicated hardware instruction when available.
Supports and of floats.
Base-2 exponential function on a floating point number. Uses a dedicated hardware instruction when available.
Supports and of floats.
Returns the natural logarithm of a floating point number. Uses a dedicated hardware instruction when available.
Supports and of floats.
Returns the logarithm to the base 2 of a floating point number. Uses a dedicated hardware instruction when available.
Supports and of floats.
Returns the logarithm to the base 10 of a floating point number. Uses a dedicated hardware instruction when available.
Supports and of floats.
Returns the absolute value of an integer or a floating point number. Uses a dedicated hardware instruction when available. The return type is always an unsigned integer of the same bit width as the operand if the operand is an integer. Unsigned integer operands are supported. The builtin cannot overflow for signed integer operands.
Supports , and of floats or integers.
Returns the largest integral value not greater than the given floating point number. Uses a dedicated hardware instruction when available.
Supports and of floats.
When the inferred result type is an , the integer part is extracted from the floored result. If that value cannot fit in the destination type, it invokes safety-checked .
Returns the smallest integral value not less than the given floating point number. Uses a dedicated hardware instruction when available.
Supports and of floats.
When the inferred result type is an , the integer part is extracted from the ceiled result. If that value cannot fit in the destination type, it invokes safety-checked .
Rounds the given floating point number to an integer, towards zero. Uses a dedicated hardware instruction when available.
Supports and of float parameters.
When the inferred result type is an , the integer part is extracted from the truncated result. If that value cannot fit in the destination type, it invokes safety-checked .
Rounds the given floating point number to the nearest integer. If two integers are equally close, rounds away from zero. Uses a dedicated hardware instruction when available.
Supports and of floats.
When the inferred result type is an , the integer part is extracted from the rounded result. If that value cannot fit in the destination type, it invokes safety-checked .
Performs and returns a tuple with the result and a possible overflow bit.
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 .
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:
When is used at file scope, it returns a reference to the struct that corresponds to the current file.
This function inserts a platform-specific trap/jam instruction which can be used to exit the program abnormally. This may be implemented by explicitly emitting an invalid instruction which may cause an illegal instruction exception of some sort. Unlike for , execution does not continue after this point.
Outside function scope, this builtin causes a compile error.
See also:
This function truncates bits from an integer type, resulting in a smaller or same-sized integer type. The return type is the inferred result type.
This function always truncates the significant bits of the integer, regardless of endianness on the target platform.
Calling on a number out of range of the destination type is well defined and working code:
Use to convert numbers guaranteed to fit the destination type.
Returns the comptime-only "enum literal" type. This is the type of uncoerced . Values of this type can coerce to any with a matching field.
Returns an integer type with the given signedness and bit width.
For instance, returns the type .
Returns a type with the given field types.
Returns a type with the properties specified by the arguments.
Returns a type with the properties specified by the arguments.
Returns a type with the properties specified by the arguments.
Returns a type with the properties specified by the arguments.
Returns an type with the properties specified by the arguments.
Returns a SPIR-V type with the properties specified by the arguments.
Provides type reflection.
Type information of , , , and has fields which are guaranteed to be in the same order as appearance in the source file.
Type information of , , , and has declarations, which are also guaranteed to be in the same order as appearance in the source file.
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.
is a special builtin function that takes any (non-zero) number of expressions as parameters and returns the type of the result, using .
The expressions are evaluated, however they are guaranteed to have no side-effects:
This is the same thing as initialization syntax, except that the field name is a -known value rather than an identifier token.
forwards its to .
Creates .
Remove qualifier from a pointer.
Returns the index of the work group in the current kernel invocation in dimension .
Returns the number of work items that a work group has in dimension .
Returns the index of the work item in the work group in dimension . This function returns values between (inclusive) and (exclusive).
Zig has four optimization modes:
To add standard build options to a file:
This causes these options to be available:
See also:
Zig has a compile option which has the following effects:
Many operations in Zig trigger what is known as "Illegal Behavior" (IB). If Illegal Behavior is detected at compile-time, Zig emits a compile error and refuses to continue. Otherwise, when Illegal Behavior is not caught at compile-time, it falls into one of two categories.
Some Illegal Behavior is : this means that the compiler will insert "safety checks" anywhere that the Illegal Behavior may occur at runtime, to determine whether it is about to happen. If it is, the safety check "fails", which triggers a panic.
All other Illegal Behavior is , meaning the compiler is unable to insert safety checks for it. If Unchecked Illegal Behavior is invoked at runtime, anything can happen: usually that will be some kind of crash, but the optimizer is free to make Unchecked Illegal Behavior do anything, such as calling arbitrary functions or clobbering arbitrary data. This is similar to the concept of "undefined behavior" in some other languages. Note that Unchecked Illegal Behavior still always results in a compile error if evaluated at , because the Zig compiler is able to perform more sophisticated checks at compile-time than at runtime.
Most Illegal Behavior is safety-checked. However, to facilitate optimizations, safety checks are disabled by default in the and optimization modes. Safety checks can also be enabled or disabled on a per-block basis, overriding the default for the current optimization mode, using . When safety checks are disabled, Safety-Checked Illegal Behavior behaves like Unchecked Illegal Behavior; that is, any behavior may result from invoking it.
When a safety check fails, Zig's default panic handler crashes with a stack trace, like this:
At compile-time:
At runtime:
At compile-time:
At runtime:
At compile-time:
At runtime:
To obtain the maximum value of an unsigned integer, use .
At compile-time:
At runtime:
To truncate bits, use .
The following operators can cause integer overflow:
Example with addition at compile-time:
At runtime:
These functions provided by the standard library return possible errors.
Example of catching an overflow for addition:
These builtins return a tuple containing whether there was an overflow (as a ) and the possibly overflowed bits of the operation:
Example of :
These operations have guaranteed wraparound semantics.
At compile-time:
At runtime:
At compile-time:
At runtime:
At compile-time:
At runtime:
At compile-time:
At runtime:
At compile-time:
At runtime:
At compile-time:
At runtime:
One way to avoid this crash is to test for null instead of assuming non-null, with the expression:
See also:
At compile-time:
At runtime:
One way to avoid this crash is to test for an error instead of assuming a successful result, with the expression:
See also:
At compile-time:
At runtime:
At compile-time:
At runtime:
At compile-time:
At runtime:
At compile-time:
At runtime:
At compile-time:
At runtime:
This safety is not available for or unions.
To change the active field of a union, assign the entire union, like this:
To change the active field of a union when a meaningful value for the field is not known, use , like this:
See also:
This happens when casting a float to an integer where the float has a value outside the integer type's range.
At compile-time:
At runtime:
This happens when casting a pointer with the address 0 to a pointer which may not have the address 0. For example, , , and pointers allow address zero, but normal do not.
At compile-time:
At runtime:
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:
Like Zig, the C programming language has manual memory management. However, unlike Zig, C has a default allocator - , , and . When linking against libc, Zig exposes this allocator with . However, by convention, there is no default allocator in Zig. Instead, functions which need to allocate accept an parameter. Likewise, some data structures accept an parameter in their initialization functions:
In the above example, 100 bytes of stack memory are used to initialize a , which is then passed to a function. As a convenience there is a global available for quick tests at , which will also perform basic leak detection.
Zig has a general purpose allocator available to be imported with . However, it is still recommended to follow the guide.
What allocator to use depends on a number of factors. Here is a flow chart to help you decide:
String literals such as 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:
However if you make the slice constant, then it works:
Just like string literals, declarations, when the value is known at , are stored in the global constant data section. Also are stored in the global constant data section.
declarations inside functions are stored in the function's stack frame. Once a function returns, any to variables in the function's stack frame become invalid references, and dereferencing them becomes unchecked .
declarations at the top level or in declarations are stored in the global data section.
The location of memory allocated with or is determined by the allocator's implementation.
TODO: thread local variables
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, 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:
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 .
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.
It is the Zig programmer's responsibility to ensure that a is not accessed when the memory pointed to is no longer available. Note that a 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 parameter.
Sometimes the lifetime of a pointer may be more complicated. For example, the 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 occur).
Compile variables are accessible by importing the 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.
Example of what is imported with :
See also:
A Zig compilation is separated into . Each module is a collection of Zig source files, one of which is the module's . Each module can on any number of other modules, forming a directed graph (dependency loops between modules are allowed). If module A depends on module B, then any Zig source file in module A can import the of module B using with the module's name. In essence, a module acts as an alias to import a Zig source file (which might exist in a completely separate part of the filesystem).
A simple Zig program compiled with has two key modules: the one containing your code, known as the "main" or "root" module, and the standard library. Your module the standard library module under the name "std", which is what allows you to write ! In fact, every single module in a Zig compilation — including the standard library itself — implicitly depends on the standard library module under the name "std".
The "root module" (the one provided by you in the example) has a special property. Like the standard library, it is implicitly made available to all modules (including itself), this time under the name "root". So, will always be equivalent to of your "main" source file (often, but not necessarily, named ).
Every Zig source file is implicitly a declaration; you can imagine that the file's contents are literally surrounded by . This means that as well as declarations, the top level of a file is permitted to contain fields:
Such files can be instantiated just like any other type. A file's "root struct type" can be referred to within that file using .
Zig places importance on the concept of whether any piece of code is ; in essence, whether the compiler "looks at" it. What code is analyzed is based on what files and declarations are "discovered" from a certain point. This process of "discovery" is based on a simple set of recursive rules:
That's it! Those rules define how Zig files and declarations are discovered. All that remains is to understand where this process .
The answer to that is the root of the standard library: every Zig compilation begins by analyzing the file . This file contains a declaration which imports , and that file in turn uses to reference the "root module"; so, the file you provide as your main module's root source file is effectively also a root, because the standard library will always reference it.
It is often desirable to make sure that certain declarations — particularly or declarations — are discovered. Based on the above rules, a common strategy for this is to use within a or block:
Because the root module's root source file is always accessible using , is is sometimes used by libraries — including the Zig Standard Library — as a place for the program to expose some "global" information to that library. The Zig Standard Library will look for several declarations in this file.
When building an executable, the most important thing to be looked up in this file is the program's . Most commonly, this is a function named , which will call just after performing important initialization work.
Alternatively, the presence of a declaration named (for instance, ) will disable the default logic, allowing your root source file to export a low-level entry point as needed.
If the Zig compilation links libc, the function can optionally be an which matches the signature of the C function:
may also use other entry point declarations in certain situations, such as or . Refer to the logic for details of these declarations.
The standard library also looks for a declaration in the root module's root source file named . If present, this declaration is expected to be a struct of type , and allows the program to customize some standard library functionality, such as the implementation.
The Zig Standard Library looks for a declaration named in the root module's root source file. If present, it is expected to be a with declarations providing different panic handlers.
See for a basic implementation of this namespace.
Overriding how the panic handler actually outputs messages, but keeping the formatted safety panics which are enabled by default, can be easily achieved with :
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:
To use the build system, run to see a command-line usage help menu. This will include project-specific options that were declared in the build.zig script.
For the time being, the build system documentation is hosted externally:
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.
These have guaranteed C ABI compatibility and can be used like any other type.
To interop with the C type, use .
See also:
Zig's C translation capability is available as a CLI tool via . It requires a single filename as an argument. It may also take a set of optional flags that are forwarded to clang. It writes the translated file to stdout.
When translating C code with , you use the same triple that you will use when compiling the translated code. In addition, you ensure that the used, if any, match the cflags used by code on the target system. Using the incorrect or could result in clang or Zig parse failures, or subtle ABI incompatibilities when linking with C code.
Some C constructs cannot be translated to Zig - for example, , structs with bitfields, and token-pasting macros. Zig employs to allow translation to continue in the face of non-translatable entities.
Demotion comes in three varieties - , , and . C structs and unions that cannot be translated correctly will be translated as . Functions that contain opaque types or code constructs that cannot be translated will be demoted to 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.
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:
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 () or many-item pointers (). C pointers are a compromise so that Zig code can utilize translated header files directly.
- C pointer.
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:
This is comparable to doing in C.
When a C pointer is pointing to an array of structs, the syntax reverts to this:
Zig supports extern variadic functions.
Variadic functions can be implemented using , , and .
One of the primary use cases for Zig is exporting a library with the C ABI for other programming languages to call into. The keyword in front of functions, variables, and types causes them to be part of the library API:
To make a static library:
To make a shared library:
Here is an example with the :
See also:
You can mix Zig object files with any other object files that respect the C ABI. Example:
See also:
Zig supports building for WebAssembly out of the box.
For host environments like the web browser and nodejs, build as an executable using the freestanding OS target. Here's an example of running Zig code compiled to WebAssembly with nodejs.
Zig standard library has first-class support for WebAssembly System Interface.
A more interesting example would be extracting the list of preopens from the runtime. This is now supported in the standard library via :
refers to the computer that will be used to run an executable. It is composed of the CPU architecture, the set of enabled CPU features, operating system, minimum and maximum operating system version, ABI, and ABI version.
Zig is a general-purpose programming language which means that it is designed to generate optimal code for a large set of targets. The command provides information about all of the targets the compiler is aware of.
When no target option is provided to the compiler, the default choice is to target the , meaning that the resulting executable will be . In order to copy an executable to another computer, the compiler needs to know about the target requirements via the option.
The Zig Standard Library () has cross-platform abstractions, making the same source code viable on many targets. Some code is more portable than other code. In general, Zig code is extremely portable compared to other programming languages.
Each platform requires its own implementations to make Zig's cross-platform abstractions work. These implementations are at various degrees of completion. Each tagged release of the compiler comes with release notes that provide the full support table for each target.
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.
Avoid these words in type names:
Everything is a value, all types are data, everything is context, all logic manages state. Nothing is communicated by using a word that applies to all types.
Temptation to use "utilities", "miscellaneous", or somebody's initials is a failure to categorize, or more commonly, overcategorization. Such declarations can live at the root of a module that needs them with no namespace needed.
Every declaration is assigned a by the compiler, creating a tree structure. Choose names based on the fully-qualified namespace, and avoid redundant name segments.
In this example, "json" is repeated in the fully-qualified namespace. The solution is to delete from . In this example we have an empty struct named but remember that files also act as part of the fully-qualified namespace.
This example is an exception to the rule specified in . The meaning of the type has been reduced to its core: it is a json value. The name cannot be any more specific without being incorrect.
In some programming languages, it is common to prefix identifiers with underscores to avoid keyword collisions, name collisions, or indicate additional metadata associated with usage of the identifier, such as: privacy, existence of complex data invariants, exclusion from semantic versioning, or context-specific type reflection meaning.
In Zig, there are no private fields, and this style guide recommends against pretending otherwise. Instead, fields should be named carefully based on their semantics and documentation should indicate how to use fields without violating data invariants. If a field is not subject to the same semantic versioning rules as everything else, the exception should be noted in the .
As for , it is less error prone and more maintainable to use the type system than to make field names meaningful.
Regarding name collisions, an underscore is insufficient to explain the difference between the two otherwise identical names. If there's no danger in getting them mixed up, then this guide recommends more verbose names at outer scopes and more abbreviated names at inner scopes.
Finally, keyword collisions are better avoided via .
Roughly speaking: , , . More precisely:
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 . Otherwise, it should use . Directory names should be .
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 , follow the established convention.
See the for more examples.
Zig source code is UTF-8 encoded. Invalid UTF-8 byte sequences are not allowed anywhere.
Some code points are never allowed, even in :
LF (byte value 0x0a, code point U+000a, ) is the line terminator in Zig source code. This byte value terminates every line of Zig source code, including last line of the file.
These conservative rules mean that third party tools reading already-validated Zig source code may make simplifying assumptions, such as naively separating lines based on . However, tooling such as provides convenience functionality to convert invalid source encodings to valid source encodings, for instance by stripping byte order marks and carriage returns.
Operator Precedence Flowchart §
To help understand the grammar, this flowchart is provided for the operator precedence. The bottom represents any location where an expression may occur and the topmost row represents a parenthesized expression. An operator will have a higher precedence (and therefore be the parent) to another node if it is strictly lower on the tree (having a directed path from one to another). This is inverted from classical precedence, but is closer to how a recursive descent parser views the grammar.
┏━━━━━━━━━━━━━━━━━━━┓
┃(expr) ┃
┃x() x[] x.y x.* x.?┃
┃E!T ┃
┃x{} ┃
┃!x -x -%x ~x &x ?x ┃
┗━━━━━━━━━▲━━━━━━━━━┛
┌─────────────┬──────┴───────┬───────┬──┬──┬─┐
│ │ │ │ │ │ │
┏━━━━━━┷━━━━━┓╭Non╌Chaining╮ ╭Non╌Chaining╮┏┷┓┏┷┓┏┷┓│
┃* *% *| / ||┃╎ % ╎ ╎ << <<| >> ╎┃&┃┃^┃┃|┃│
┗━━━━━━▲━━━━━┛╰╌╌╌╌╌╌▲╌╌╌╌╌╯ ╰╌╌╌╌╌╌▲╌╌╌╌╌╯┗▲┛┗▲┛┗▲┛│
┏━━┷━━━━━━━━━━━━━┷━┓ ┌────┴───────┴──┴──┘ │
┃+ - +% -% +| -| ++┃ │ │
┗━━━━━━━━━━━▲━━━━━━┛ │ │
╭┴╌Non-Chaining╌┴╮ │
╎== != < <= >= >╎ │
╰╌╌╌▲╌╌╌╌▲╌╌╌╌╌╌╌╯ ┌──────┬─────┘
┏━┷━┓┏━┷━┓ ┏━━━┷━━┓┏━━┷━━┓
┃and┃┃or ┃ ┃orelse┃┃catch┃
┗━▲━┛┗━▲━┛ ┗━━━▲━━┛┗━━▲━━┛
╭╌╌┴╌╌╌╌┴╌╌╌╌╌╌╌╌╌╌╌╌╌╌┴╌╌╌╌╌╌┴╌╮
╎ Any expression location ╎
╰╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╯