2017-11-07 08:22:27 +00:00
<!doctype html>
2019-12-05 21:38:59 +00:00
< html lang = "en" >
2017-11-07 08:22:27 +00:00
< head >
< meta charset = "utf-8" >
2020-07-27 15:10:55 +01:00
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
2017-11-07 08:22:27 +00:00
< title > Documentation - The Zig Programming Language< / title >
2019-10-03 16:15:55 +01:00
< link rel = "icon" href = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAgklEQVR4AWMYWuD7EllJIM4G4g4g5oIJ/odhOJ8wToOxSTXgNxDHoeiBMfA4+wGShjyYOCkG/IGqWQziEzYAoUAeiF9D5U+DxEg14DRU7jWIT5IBIOdCxf+A+CQZAAoopEB7QJwBCBwHiip8UYmRdrAlDpIMgApwQZNnNii5Dq0MBgCxxycBnwEd+wAAAABJRU5ErkJggg==" / >
2019-12-05 21:38:59 +00:00
< style >
2018-10-24 03:11:31 +01:00
body{
2019-02-22 15:56:49 +00:00
font-family: system-ui, -apple-system, Roboto, "Segoe UI", sans-serif;
2019-10-23 11:55:20 +01:00
margin: 0;
2018-10-24 03:11:31 +01:00
}
2019-04-09 04:54:36 +01:00
a:not(:hover) {
2018-10-24 03:11:31 +01:00
text-decoration: none;
}
2017-11-07 08:22:27 +00:00
table, th, td {
border-collapse: collapse;
border: 1px solid grey;
}
th, td {
padding: 0.1em;
}
2018-01-19 08:03:20 +00:00
.t0_1, .t37, .t37_1 {
font-weight: bold;
}
.t2_0 {
color: grey;
}
.t31_1 {
color: red;
}
.t32_1 {
color: green;
}
.t36_1 {
color: #0086b3;
}
.file {
text-decoration: underline;
}
2019-04-03 22:39:07 +01:00
pre,code {
2018-01-19 08:03:20 +00:00
font-size: 12pt;
}
2018-01-30 04:33:38 +00:00
pre > code {
display: block;
overflow: auto;
2018-09-12 22:26:51 +01:00
padding: 0.5em;
2019-04-03 22:39:07 +01:00
color: #333;
background: #f8f8f8;
2018-01-30 04:33:38 +00:00
}
.table-wrapper {
width: 100%;
overflow-y: auto;
}
2018-09-12 22:26:51 +01:00
.tok-kw {
2019-04-03 22:39:07 +01:00
color: #333;
2018-09-12 22:26:51 +01:00
font-weight: bold;
}
.tok-str {
2019-04-03 22:39:07 +01:00
color: #d14;
2018-09-12 22:26:51 +01:00
}
.tok-builtin {
2019-04-03 22:39:07 +01:00
color: #0086b3;
2018-09-12 22:26:51 +01:00
}
.tok-comment {
2019-04-03 22:39:07 +01:00
color: #777;
2018-09-12 22:26:51 +01:00
font-style: italic;
}
.tok-fn {
2019-04-03 22:39:07 +01:00
color: #900;
2018-09-12 22:26:51 +01:00
font-weight: bold;
}
.tok-null {
2019-04-03 22:39:07 +01:00
color: #008080;
2018-09-12 22:26:51 +01:00
}
.tok-number {
2019-04-03 22:39:07 +01:00
color: #008080;
2018-09-12 22:26:51 +01:00
}
.tok-type {
2019-04-03 22:39:07 +01:00
color: #458;
2018-09-12 22:26:51 +01:00
font-weight: bold;
}
2019-10-23 11:55:20 +01:00
#main-wrapper {
display: flex;
flex-direction: column;
height: 100vh;
}
#contents-wrapper {
flex-grow: 1;
padding: 0 2em;
}
2019-04-03 22:39:07 +01:00
#contents {
max-width: 60em;
margin: auto;
2017-11-07 08:22:27 +00:00
}
2019-04-03 22:39:07 +01:00
2020-07-08 05:42:02 +01:00
#toc {
2019-10-23 11:55:20 +01:00
padding: 0 1em;
}
@media screen and (min-width: 1025px) {
#main-wrapper {
flex-direction: row;
}
2020-07-08 05:42:02 +01:00
#contents-wrapper, #toc {
2019-10-23 11:55:20 +01:00
overflow: auto;
}
}
2018-10-24 03:11:31 +01:00
h1 a, h2 a, h3 a, h4 a, h5 a {
text-decoration: none;
2019-04-03 22:39:07 +01:00
color: #333;
2018-10-24 03:11:31 +01:00
}
2019-04-03 22:39:07 +01:00
a.hdr {
visibility: hidden;
}
h1:hover > a.hdr, h2:hover > a.hdr, h3:hover > a.hdr, h4:hover > a.hdr, h5:hover > a.hdr {
visibility: visible;
}
@media (prefers-color-scheme: dark) {
body{
background-color:#111;
color: #bbb;
}
a {
color: #88f;
}
table, th, td {
border-color: grey;
}
.t2_0 {
color: grey;
}
.t31_1 {
color: red;
}
.t32_1 {
color: green;
}
.t36_1 {
color: #0086b3;
}
pre > code {
color: #ccc;
background: #222;
}
.tok-kw {
color: #eee;
}
.tok-str {
color: #2e5;
}
.tok-builtin {
color: #ff894c;
}
.tok-comment {
color: #aa7;
}
.tok-fn {
color: #e33;
}
.tok-null {
color: #ff8080;
}
.tok-number {
color: #ff8080;
}
.tok-type {
color: #68f;
}
h1 a, h2 a, h3 a, h4 a, h5 a {
color: #aaa;
}
2018-10-24 03:11:31 +01:00
}
2017-11-07 08:22:27 +00:00
< / style >
< / head >
< body >
2019-10-23 11:55:20 +01:00
< div id = "main-wrapper" >
2020-07-08 05:42:02 +01:00
< div id = "toc" >
2020-04-14 02:33:08 +01:00
< a href = "https://ziglang.org/documentation/0.1.1/" > 0.1.1< / a > |
< a href = "https://ziglang.org/documentation/0.2.0/" > 0.2.0< / a > |
< a href = "https://ziglang.org/documentation/0.3.0/" > 0.3.0< / a > |
< a href = "https://ziglang.org/documentation/0.4.0/" > 0.4.0< / a > |
< a href = "https://ziglang.org/documentation/0.5.0/" > 0.5.0< / a > |
< a href = "https://ziglang.org/documentation/0.6.0/" > 0.6.0< / a > |
2019-10-23 11:55:20 +01:00
master
2020-07-08 05:42:02 +01:00
< h1 > Contents< / h1 >
2019-10-23 11:55:20 +01:00
{#nav#}
< / div >
< div id = "contents-wrapper" > < div id = "contents" >
2018-01-17 04:19:05 +00:00
{#header_open|Introduction#}
2017-11-07 08:22:27 +00:00
< p >
2019-12-30 23:16:40 +00:00
Zig is a general-purpose programming language and toolchain for maintaining
< strong > robust< / strong > , < strong > optimal< / strong > , and < strong > reusable< / strong > software.
2017-11-07 08:22:27 +00:00
< / p >
< ul >
< li > < strong > Robust< / strong > - behavior is correct even for edge cases such as out of memory.< / li >
< li > < strong > Optimal< / strong > - write programs the best way they can behave and perform.< / li >
2019-11-13 18:44:19 +00:00
< li > < strong > Reusable< / strong > - the same code works in many environments which have different
constraints.< / li >
< li > < strong > Maintainable< / strong > - precisely communicate intent to the compiler and
other programmers. The language imposes a low overhead to reading code and is
resilient to changing requirements and environments.< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< p >
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.
< / p >
< p >
If you search for something specific in this documentation and do not find it,
2018-05-25 02:27:44 +01:00
please < a href = "https://github.com/ziglang/www.ziglang.org/issues/new?title=I%20searched%20for%20___%20in%20the%20docs%20and%20didn%27t%20find%20it" > file an issue< / a > or < a href = "https://webchat.freenode.net/?channels=%23zig" > say something on IRC< / a > .
2017-11-07 08:22:27 +00:00
< / p >
2018-01-19 08:03:20 +00:00
< p >
The code samples in this document are compiled and tested as part of the main test suite of Zig.
2020-07-09 12:38:02 +01:00
< / p >
< p >
2018-01-19 08:03:20 +00:00
This HTML document depends on no external files, so you can use it offline.
< / p >
2019-07-02 20:21:03 +01:00
< p >
< a href = "https://github.com/ziglang/zig/wiki/FAQ#where-is-the-documentation-for-the-zig-standard-library" > Where is the documentation for the Zig standard library?< / a >
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2019-04-03 22:39:07 +01:00
2018-01-17 04:19:05 +00:00
{#header_open|Hello World#}
2017-11-07 08:22:27 +00:00
2018-01-17 06:50:35 +00:00
{#code_begin|exe|hello#}
const std = @import("std");
2018-02-08 08:02:41 +00:00
pub fn main() !void {
2020-07-13 09:29:46 +01:00
const stdout = std.io.getStdOut().writer();
2019-12-09 04:46:50 +00:00
try stdout.print("Hello, {}!\n", .{"world"});
2018-01-17 06:50:35 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2020-07-09 12:38:02 +01:00
The Zig code sample above demonstrates one way to create a program that will output < code > Hello, world!< / code > .
2017-11-07 08:22:27 +00:00
< / p >
2020-07-09 12:38:02 +01:00
< p >
The code sample shows the contents of a file named < code > hello.zig< / code > . Files storing Zig
source code are {#link|UTF-8 encoded|Source Encoding#} text files. The files storing
Zig source code are usually named with the < code > .zig< / code > extension.
< / p >
< p >
Following the < code > hello.zig< / code > Zig code sample, the {#link|Zig Build System#} is used
2020-06-29 01:42:37 +01:00
to build an executable program from the < code > hello.zig< / code > source code. Then, the
2020-07-09 12:38:02 +01:00
< code > hello< / code > program is executed showing its output < code > Hello, world!< / code > . The
lines beginning with < code > $< / code > represent command line prompts and a command.
Everything else is program output.
< / p >
< p >
The code sample begins by adding Zig's Standard Library to the build using the {#link|@import#} builtin function.
The {#syntax#}@import("std"){#endsyntax#} function call creates a structure to represent the Standard Library.
The code then makes a {#link|top-level declaration|Global Variables#} of a
{#link|constant identifier|Assignment#}, named < code > std< / code > , for easy access to
< a href = "https://github.com/ziglang/zig/wiki/FAQ#where-is-the-documentation-for-the-zig-standard-library" > Zig's standard library< / a > .
< / p >
< p >
Next, a {#link|public function|Functions#}, {#syntax#}pub fn{#endsyntax#}, named < code > main< / code >
is declared. The < code > main< / code > function is necessary because it tells the Zig compiler where the start of
the program exists. Programs designed to be executed will need a {#syntax#}pub fn main{#endsyntax#} function.
2020-07-11 03:10:08 +01:00
For more advanced use cases, Zig offers other features to inform the compiler where the start of
2020-07-09 12:38:02 +01:00
the program exists. Libraries, on the other hand, do not need a < code > main< / code > function because
library code is usually called by other programs.
< / p >
< p >
A function is a block of any number of statements and expressions that, as a whole, perform a task.
2020-07-11 12:08:00 +01:00
Functions may or may not return data after they are done performing their task. If a function
cannot perform its task, it might return an error. Zig makes all of this explicit.
2020-07-09 12:38:02 +01:00
< / p >
< p >
In the < code > hello.zig< / code > code sample, the < code > main< / code > function is declared
2020-07-11 12:08:00 +01:00
with the {#syntax#}!void{#endsyntax#} return type. This return type is known as an {#link|Error Union Type#}.
This syntax tells the Zig compiler that the function will either return an
error or a value. An error union type combines an {#link|Error Set Type#} and a {#link|Primitive Type|Primitive Types#}.
The full form of an error union type is
< code > < error set type> < / code > {#syntax#}!{#endsyntax#}< code > < primitive type> < / code > . In the code
sample, the error set type is not explicitly written on the left side of the {#syntax#}!{#endsyntax#} operator.
When written this way, the error set type is a special kind of error union type that has an
{#link|inferred error set type|Inferred Error Sets#}. The {#syntax#}void{#endsyntax#} after the {#syntax#}!{#endsyntax#} operator
tells the compiler that the function will not return a value under normal circumstances (i.e. no errors occur).
< / p >
< p >
Note to experienced programmers: Zig also has the boolean {#link|operator|Operators#} {#syntax#}!a{#endsyntax#}
where {#syntax#}a{#endsyntax#} is a value of type {#syntax#}bool{#endsyntax#}. Error union types contain the
name of the type in the syntax: {#syntax#}!{#endsyntax#}< code > < primitive type> < / code > .
2020-07-09 12:38:02 +01:00
< / p >
< p >
In Zig, a function's block of statements and expressions are surrounded by < code > {< / code > and
< code > }< / code > curly-braces. Inside of the < code > main< / code > function are expressions that perform
2020-06-29 01:42:37 +01:00
the task of outputting < code > Hello, world!< / code > to standard output.
2020-07-09 12:38:02 +01:00
< / p >
< p >
2020-07-11 12:08:00 +01:00
First, a constant identifier, < code > stdout< / code > , is initialized to represent standard output's
writer. Then, the program tries to print the < code > Hello, world!< / code >
message to standard output.
2020-07-09 12:38:02 +01:00
< / p >
< p >
Functions sometimes need information to perform their task. In Zig, information is passed
to functions between open < code > (< / code > and close < code > )< / code > parenthesis placed after
2020-07-11 03:09:57 +01:00
the function's name. This information is also known as arguments. When there are
2020-07-09 12:38:02 +01:00
multiple arguments passed to a function, they are separated by commas < code > ,< / code > .
< / p >
< p >
The two arguments passed to the < code > stdout.print()< / code > function, < code > "Hello, {}!\n"< / code >
and < code > .{"world"}< / code > , are evaluated at {#link|compile-time|comptime#}. The code sample is
purposely written to show how to perform {#link|string|String Literals and Character Literals#}
substitution in the < code > print< / code > function. The curly-braces inside of the first argument
are substituted with the compile-time known value inside of the second argument
(known as an {#link|anonymous struct literal|Anonymous Struct Literals#}). The < code > \n< / code >
inside of the double-quotes of the first argument is the {#link|escape sequence|Escape Sequences#} for the
newline character. The {#link|try#} expression evaluates the result of < code > stdout.print< / code > .
If the result is an error, then the {#syntax#}try{#endsyntax#} expression will return from
< code > main< / code > with the error. Otherwise, the program will continue. In this case, there are no
more statements or expressions left to execute in the < code > main< / code > function, so the program exits.
< / p >
< p >
2020-07-11 12:08:00 +01:00
In Zig, the standard output writer's < code > print< / code > function is allowed to fail because
it is actually a function defined as part of a generic Writer. Consider a generic Writer that
represents writing data to a file. When the disk is full, a write to the file will fail.
However, we typically do not expect writing text to the standard output to fail. To avoid having
to handle the failure case of printing to standard output, you can use alternate functions: the
2020-08-13 16:12:16 +01:00
functions in < code > std.log< / code > for proper logging or the < code > std.debug.print< / code > function.
2020-07-11 12:08:00 +01:00
This documentation will use the latter option to print to standard error (stderr) and silently return
on failure. The next code sample, < code > hello_again.zig< / code > demonstrates the use of
2020-07-09 12:38:02 +01:00
< code > std.debug.print< / code > .
< / p >
{#code_begin|exe|hello_again#}
2020-06-19 10:38:22 +01:00
const print = @import("std").debug.print;
2017-11-07 08:22:27 +00:00
2018-01-25 09:10:11 +00:00
pub fn main() void {
2020-06-19 10:38:22 +01:00
print("Hello, world!\n", .{});
2018-01-17 06:50:35 +00:00
}
{#code_end#}
2018-01-23 04:06:07 +00:00
< p >
2020-07-09 12:38:02 +01:00
Note that you can leave off the {#syntax#}!{#endsyntax#} from the return type because < code > std.debug.print< / code > cannot fail.
2018-01-23 04:06:07 +00:00
< / p >
2020-07-09 12:38:02 +01:00
{#see_also|Values|@import|Errors|Root Source File|Source Encoding#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-07-31 03:27:07 +01:00
{#header_open|Comments#}
{#code_begin|test|comments#}
const assert = @import("std").debug.assert;
test "comments" {
// Comments in Zig start with "//" and end at the next LF byte (end of line).
// The below line is a comment, and won't be executed.
//assert(false);
const x = true; // another comment
assert(x);
}
{#code_end#}
< p >
2018-09-14 15:35:03 +01:00
There are no multiline comments in Zig (e.g. like < code class = "c" > /* */< / code >
2018-07-31 03:27:07 +01:00
comments in C). This helps allow Zig to have the property that each line
of code can be tokenized out of context.
< / p >
{#header_open|Doc comments#}
< p >
A doc comment is one that begins with exactly three slashes (i.e.
2018-09-14 15:35:03 +01:00
{#syntax#}///{#endsyntax#} but not {#syntax#}////{#endsyntax#});
2018-07-31 03:27:07 +01:00
multiple doc comments in a row are merged together to form a multiline
doc comment. The doc comment documents whatever immediately follows it.
< / p >
{#code_begin|syntax|doc_comments#}
/// A structure for storing a timestamp, with nanosecond precision (this is a
/// multiline doc comment).
2018-11-13 13:08:37 +00:00
const Timestamp = struct {
2018-07-31 03:27:07 +01:00
/// The number of seconds since the epoch (this is also a doc comment).
seconds: i64, // signed so we can represent pre-1970 (not a doc comment)
/// The number of nanoseconds past the second (doc comment again).
nanos: u32,
/// Returns a `Timestamp` struct representing the Unix epoch; that is, the
/// moment of 1970 Jan 1 00:00:00 UTC (this is a doc comment too).
pub fn unixEpoch() Timestamp {
2018-11-13 13:08:37 +00:00
return Timestamp{
2018-07-31 03:27:07 +01:00
.seconds = 0,
.nanos = 0,
};
}
};
{#code_end#}
< p >
Doc comments are only allowed in certain places; eventually, it will
2019-06-11 19:31:03 +01:00
become a compile error to have a doc comment in an unexpected place, such as
2018-07-31 03:27:07 +01:00
in the middle of an expression, or just before a non-doc comment.
< / p >
{#header_close#}
2020-07-05 23:39:28 +01:00
{#header_open|Top-Level Doc Comments#}
< p > User documentation that doesn't belong to whatever
immediately follows it, like package-level documentation, goes
in top-level doc comments. A top-level doc comment is one that
begins with two slashes and an exclamation point:
{#syntax#}//!{#endsyntax#}.< / p >
{#code_begin|syntax|tldoc_comments#}
//! This module provides functions for retrieving the current date and
//! time with varying degrees of precision and accuracy. It does not
//! depend on libc, but will use functions from it if available.
{#code_end#}
{#header_close#}
2018-07-31 03:27:07 +01:00
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|Values#}
2018-01-17 08:24:03 +00:00
{#code_begin|exe|values#}
2019-02-18 22:41:55 +00:00
// Top-level declarations are order-independent:
2020-06-19 10:38:22 +01:00
const print = std.debug.print;
2019-02-18 22:41:55 +00:00
const std = @import("std");
2018-01-17 08:24:03 +00:00
const os = std.os;
const assert = std.debug.assert;
2017-11-07 08:22:27 +00:00
2018-02-08 08:02:41 +00:00
pub fn main() void {
2017-11-07 08:22:27 +00:00
// integers
const one_plus_one: i32 = 1 + 1;
2020-06-19 10:38:22 +01:00
print("1 + 1 = {}\n", .{one_plus_one});
2017-11-07 08:22:27 +00:00
// floats
const seven_div_three: f32 = 7.0 / 3.0;
2020-06-19 10:38:22 +01:00
print("7.0 / 3.0 = {}\n", .{seven_div_three});
2017-11-07 08:22:27 +00:00
// boolean
2020-06-19 10:38:22 +01:00
print("{}\n{}\n{}\n", .{
2017-11-07 08:22:27 +00:00
true and false,
true or false,
2019-12-09 04:46:50 +00:00
!true,
});
2019-02-22 15:56:49 +00:00
2018-06-10 04:42:14 +01:00
// optional
var optional_value: ?[]const u8 = null;
assert(optional_value == null);
2017-11-07 08:22:27 +00:00
2020-06-19 10:38:22 +01:00
print("\noptional 1\ntype: {}\nvalue: {}\n", .{
2019-12-09 20:59:42 +00:00
@typeName(@TypeOf(optional_value)),
2019-12-09 04:46:50 +00:00
optional_value,
});
2017-11-07 08:22:27 +00:00
2018-06-10 04:42:14 +01:00
optional_value = "hi";
assert(optional_value != null);
2017-11-07 08:22:27 +00:00
2020-06-19 10:38:22 +01:00
print("\noptional 2\ntype: {}\nvalue: {}\n", .{
2019-12-09 20:59:42 +00:00
@typeName(@TypeOf(optional_value)),
2019-12-09 04:46:50 +00:00
optional_value,
});
2017-11-07 08:22:27 +00:00
// error union
2018-11-13 13:08:37 +00:00
var number_or_error: anyerror!i32 = error.ArgNotFound;
2017-11-07 08:22:27 +00:00
2020-06-19 10:38:22 +01:00
print("\nerror union 1\ntype: {}\nvalue: {}\n", .{
2019-12-09 20:59:42 +00:00
@typeName(@TypeOf(number_or_error)),
2019-12-09 04:46:50 +00:00
number_or_error,
});
2019-02-22 15:56:49 +00:00
2017-11-07 08:22:27 +00:00
number_or_error = 1234;
2020-06-19 10:38:22 +01:00
print("\nerror union 2\ntype: {}\nvalue: {}\n", .{
2019-12-09 20:59:42 +00:00
@typeName(@TypeOf(number_or_error)),
2019-12-09 04:46:50 +00:00
number_or_error,
});
2018-01-17 08:24:03 +00:00
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_open|Primitive Types#}
2018-01-30 04:33:38 +00:00
< div class = "table-wrapper" >
2017-11-07 08:22:27 +00:00
< table >
< tr >
< th >
Name
< / th >
< th >
C Equivalent
< / th >
< th >
Description
< / th >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}i8{#endsyntax#}< / td >
< td > < code class = "c" > int8_t< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > signed 8-bit integer< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}u8{#endsyntax#}< / td >
< td > < code class = "c" > uint8_t< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > unsigned 8-bit integer< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}i16{#endsyntax#}< / td >
< td > < code class = "c" > int16_t< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > signed 16-bit integer< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}u16{#endsyntax#}< / td >
< td > < code class = "c" > uint16_t< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > unsigned 16-bit integer< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}i32{#endsyntax#}< / td >
< td > < code class = "c" > int32_t< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > signed 32-bit integer< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}u32{#endsyntax#}< / td >
< td > < code class = "c" > uint32_t< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > unsigned 32-bit integer< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}i64{#endsyntax#}< / td >
< td > < code class = "c" > int64_t< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > signed 64-bit integer< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}u64{#endsyntax#}< / td >
< td > < code class = "c" > uint64_t< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > unsigned 64-bit integer< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}i128{#endsyntax#}< / td >
< td > < code class = "c" > __int128< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > signed 128-bit integer< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}u128{#endsyntax#}< / td >
< td > < code class = "c" > unsigned __int128< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > unsigned 128-bit integer< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}isize{#endsyntax#}< / td >
< td > < code class = "c" > intptr_t< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > signed pointer sized integer< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}usize{#endsyntax#}< / td >
< td > < code class = "c" > uintptr_t< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > unsigned pointer sized integer< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}c_short{#endsyntax#}< / td >
< td > < code class = "c" > short< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}c_ushort{#endsyntax#}< / td >
< td > < code class = "c" > unsigned short< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}c_int{#endsyntax#}< / td >
< td > < code class = "c" > int< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}c_uint{#endsyntax#}< / td >
< td > < code class = "c" > unsigned int< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}c_long{#endsyntax#}< / td >
< td > < code class = "c" > long< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}c_ulong{#endsyntax#}< / td >
< td > < code class = "c" > unsigned long< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}c_longlong{#endsyntax#}< / td >
< td > < code class = "c" > long long< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}c_ulonglong{#endsyntax#}< / td >
< td > < code class = "c" > unsigned long long< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}c_longdouble{#endsyntax#}< / td >
< td > < code class = "c" > long double< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}c_void{#endsyntax#}< / td >
< td > < code class = "c" > void< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > for ABI compatibility with C< / td >
< / tr >
2018-06-27 17:59:12 +01:00
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}f16{#endsyntax#}< / td >
2018-09-24 18:08:21 +01:00
< td > < code class = "c" > _Float16< / code > < / td >
2018-06-27 17:59:12 +01:00
< td > 16-bit floating point (10-bit mantissa) IEEE-754-2008 binary16< / td >
< / tr >
2017-11-07 08:22:27 +00:00
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}f32{#endsyntax#}< / td >
< td > < code class = "c" > float< / code > < / td >
2018-06-17 00:53:52 +01:00
< td > 32-bit floating point (23-bit mantissa) IEEE-754-2008 binary32< / td >
2017-11-07 08:22:27 +00:00
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}f64{#endsyntax#}< / td >
< td > < code class = "c" > double< / code > < / td >
2018-06-17 00:53:52 +01:00
< td > 64-bit floating point (52-bit mantissa) IEEE-754-2008 binary64< / td >
2017-11-07 08:22:27 +00:00
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}f128{#endsyntax#}< / td >
2018-09-24 18:08:21 +01:00
< td > < code class = "c" > _Float128< / code > < / td >
2018-06-17 00:53:52 +01:00
< td > 128-bit floating point (112-bit mantissa) IEEE-754-2008 binary128< / td >
2017-11-07 08:22:27 +00:00
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}bool{#endsyntax#}< / td >
< td > < code class = "c" > bool< / code > < / td >
< td > {#syntax#}true{#endsyntax#} or {#syntax#}false{#endsyntax#}< / td >
2017-11-07 08:22:27 +00:00
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}void{#endsyntax#}< / td >
2017-11-07 08:22:27 +00:00
< td > (none)< / td >
< td > 0 bit type< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}noreturn{#endsyntax#}< / td >
2017-11-07 08:22:27 +00:00
< td > (none)< / td >
2018-09-14 15:35:03 +01:00
< td > the type of {#syntax#}break{#endsyntax#}, {#syntax#}continue{#endsyntax#}, {#syntax#}return{#endsyntax#}, {#syntax#}unreachable{#endsyntax#}, and {#syntax#}while (true) {}{#endsyntax#}< / td >
2017-11-07 08:22:27 +00:00
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}type{#endsyntax#}< / td >
2017-11-07 08:22:27 +00:00
< td > (none)< / td >
< td > the type of types< / td >
< / tr >
< tr >
2018-11-13 13:08:37 +00:00
< td > {#syntax#}anyerror{#endsyntax#}< / td >
2017-11-07 08:22:27 +00:00
< td > (none)< / td >
< td > an error code< / td >
< / tr >
2018-06-17 00:53:52 +01:00
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}comptime_int{#endsyntax#}< / td >
2018-06-17 00:53:52 +01:00
< td > (none)< / td >
< td > Only allowed for {#link|comptime#}-known values. The type of integer literals.< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}comptime_float{#endsyntax#}< / td >
2018-06-17 00:53:52 +01:00
< td > (none)< / td >
< td > Only allowed for {#link|comptime#}-known values. The type of float literals.< / td >
< / tr >
2017-11-07 08:22:27 +00:00
< / table >
2018-01-30 04:33:38 +00:00
< / div >
2018-08-25 22:39:43 +01:00
< p >
In addition to the integer types above, arbitrary bit-width integers can be referenced by using
2019-12-05 21:38:59 +00:00
an identifier of < code > i< / code > or < code > u< / code > followed by digits. For example, the identifier
2018-11-06 16:09:14 +00:00
{#syntax#}i7{#endsyntax#} refers to a signed 7-bit integer. The maximum allowed bit-width of an
integer type is {#syntax#}65535{#endsyntax#}.
2018-08-25 22:39:43 +01:00
< / p >
2020-02-24 21:39:03 +00:00
{#see_also|Integers|Floats|void|Errors|@Type#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Primitive Values#}
2018-01-30 04:33:38 +00:00
< div class = "table-wrapper" >
2017-11-07 08:22:27 +00:00
< table >
< tr >
< th >
Name
< / th >
< th >
Description
< / th >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}true{#endsyntax#} and {#syntax#}false{#endsyntax#}< / td >
< td > {#syntax#}bool{#endsyntax#} values< / td >
2017-11-07 08:22:27 +00:00
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}null{#endsyntax#}< / td >
< td > used to set an optional type to {#syntax#}null{#endsyntax#}< / td >
2017-11-07 08:22:27 +00:00
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > {#syntax#}undefined{#endsyntax#}< / td >
2017-11-07 08:22:27 +00:00
< td > used to leave a value unspecified< / td >
< / tr >
< / table >
2018-01-30 04:33:38 +00:00
< / div >
2018-09-24 18:08:21 +01:00
{#see_also|Optionals|undefined#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2019-03-23 21:35:21 +00:00
{#header_open|String Literals and Character Literals#}
< p >
2019-11-20 22:11:07 +00:00
String literals are single-item constant {#link|Pointers#} to null-terminated UTF-8 encoded byte arrays.
The type of string literals encodes both the length, and the fact that they are null-terminated,
and thus they can be {#link|coerced|Type Coercion#} to both {#link|Slices#} and
2019-11-24 03:29:12 +00:00
{#link|Null-Terminated Pointers|Sentinel-Terminated Pointers#}.
Dereferencing string literals converts them to {#link|Arrays#}.
2019-03-23 21:35:21 +00:00
< / p >
< p >
Character literals have type {#syntax#}comptime_int{#endsyntax#}, the same as
{#link|Integer Literals#}. All {#link|Escape Sequences#} are valid in both string literals
2019-10-06 18:52:35 +01:00
and character literals.
2019-03-23 21:35:21 +00:00
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
const mem = @import("std").mem;
test "string literals" {
2019-11-20 22:11:07 +00:00
const bytes = "hello";
2019-12-09 20:59:42 +00:00
assert(@TypeOf(bytes) == *const [5:0]u8);
2019-11-20 22:11:07 +00:00
assert(bytes.len == 5);
assert(bytes[1] == 'e');
assert(bytes[5] == 0);
2017-11-07 08:22:27 +00:00
assert('e' == '\x65');
2019-07-05 06:52:17 +01:00
assert('\u{1f4a9}' == 128169);
2019-10-06 18:52:35 +01:00
assert('💯' == 128175);
2017-11-07 08:22:27 +00:00
assert(mem.eql(u8, "hello", "h\x65llo"));
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2019-03-23 21:35:21 +00:00
{#see_also|Arrays|Zig Test|Source Encoding#}
2018-01-17 04:19:05 +00:00
{#header_open|Escape Sequences#}
2018-01-30 04:33:38 +00:00
< div class = "table-wrapper" >
2017-11-07 08:22:27 +00:00
< table >
< tr >
< th >
Escape Sequence
< / th >
< th >
Name
< / th >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < code > \n< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > Newline< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < code > \r< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > Carriage Return< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < code > \t< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > Tab< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < code > \\< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > Backslash< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < code > \'< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > Single Quote< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < code > \"< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > Double Quote< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < code > \xNN< / code > < / td >
2017-11-07 08:22:27 +00:00
< td > hexadecimal 8-bit character code (2 digits)< / td >
< / tr >
< tr >
2019-07-05 06:52:17 +01:00
< td > < code > \u{NNNNNN}< / code > < / td >
< td > hexadecimal Unicode character code UTF-8 encoded (1 or more digits)< / td >
2017-11-07 08:22:27 +00:00
< / tr >
< / table >
2018-01-30 04:33:38 +00:00
< / div >
2018-09-14 15:35:03 +01:00
< p > Note that the maximum valid Unicode point is {#syntax#}0x10ffff{#endsyntax#}.< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Multiline String Literals#}
2017-11-07 08:22:27 +00:00
< p >
Multiline string literals have no escapes and can span across multiple lines.
2018-09-14 15:35:03 +01:00
To start a multiline string literal, use the {#syntax#}\\{#endsyntax#} token. Just like a comment,
2017-11-07 08:22:27 +00:00
the string literal goes until the end of the line. The end of the line is
not included in the string literal.
2018-09-14 15:35:03 +01:00
However, if the next line begins with {#syntax#}\\{#endsyntax#} then a newline is appended and
2017-11-07 08:22:27 +00:00
the string literal continues.
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
const hello_world_in_c =
\\#include < stdio.h >
2017-11-07 08:22:27 +00:00
\\
\\int main(int argc, char **argv) {
\\ printf("hello world\n");
\\ return 0;
\\}
2018-01-19 08:03:20 +00:00
;
{#code_end#}
2018-01-17 05:22:33 +00:00
{#see_also|@embedFile#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_close#}
{#header_open|Assignment#}
2018-09-14 15:35:03 +01:00
< p > Use the {#syntax#}const{#endsyntax#} keyword to assign a value to an identifier:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|cannot assign to constant#}
const x = 1234;
2017-11-07 08:22:27 +00:00
2018-01-25 09:10:11 +00:00
fn foo() void {
2017-11-07 08:22:27 +00:00
// It works at global scope as well as inside functions.
const y = 5678;
// Once assigned, an identifier cannot be changed.
y += 1;
}
test "assignment" {
foo();
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-09-14 15:35:03 +01:00
< p > {#syntax#}const{#endsyntax#} applies to all of the bytes that the identifier immediately addresses. {#link|Pointers#} have their own const-ness.< / p >
< p > If you need a variable that you can modify, use the {#syntax#}var{#endsyntax#} keyword:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
test "var" {
var y: i32 = 5678;
y += 1;
assert(y == 5679);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p > Variables must be initialized:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err#}
test "initialization" {
2017-11-07 08:22:27 +00:00
var x: i32;
x = 1;
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-06-14 23:12:05 +01:00
{#header_open|undefined#}
2018-09-14 15:35:03 +01:00
< p > Use {#syntax#}undefined{#endsyntax#} to leave variables uninitialized:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
test "init with undefined" {
var x: i32 = undefined;
x = 1;
assert(x == 1);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-03 19:03:27 +01:00
< p >
2019-11-08 20:56:21 +00:00
{#syntax#}undefined{#endsyntax#} can be {#link|coerced|Type Coercion#} to any type.
2018-09-14 15:35:03 +01:00
Once this happens, it is no longer possible to detect that the value is {#syntax#}undefined{#endsyntax#}.
{#syntax#}undefined{#endsyntax#} means the value could be anything, even something that is nonsense
according to the type. Translated into English, {#syntax#}undefined{#endsyntax#} means "Not a meaningful
2018-07-03 19:03:27 +01:00
value. Using this value would be a bug. The value will be unused, or overwritten before being used."
< / p >
< p >
2018-09-14 15:35:03 +01:00
In {#link|Debug#} mode, Zig writes {#syntax#}0xaa{#endsyntax#} bytes to undefined memory. This is to catch
2018-07-03 19:03:27 +01:00
bugs early, and to help detect use of undefined memory in a debugger.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_close#}
2018-06-14 23:12:05 +01:00
{#header_close#}
2019-04-04 17:26:47 +01:00
{#header_open|Variables#}
< p >
A variable is a unit of {#link|Memory#} storage.
< / p >
< p >
Variables are never allowed to shadow identifiers from an outer scope.
< / p >
< p >
It is generally preferable to use {#syntax#}const{#endsyntax#} rather than
{#syntax#}var{#endsyntax#} when declaring a variable. This causes less work for both
humans and computers to do when reading code, and creates more optimization opportunities.
< / p >
{#header_open|Global Variables#}
< p >
Global variables are considered to be a top level declaration, which means that they are
order-independent and lazily analyzed. The initialization value of global variables is implicitly
{#link|comptime#}. If a global variable is {#syntax#}const{#endsyntax#} then its value is
{#syntax#}comptime{#endsyntax#}-known, otherwise it is runtime-known.
< / p >
{#code_begin|test|global_variables#}
var y: i32 = add(10, x);
const x: i32 = add(12, 34);
test "global variables" {
assert(x == 46);
assert(y == 56);
}
fn add(a: i32, b: i32) i32 {
return a + b;
}
const std = @import("std");
const assert = std.debug.assert;
{#code_end#}
< p >
Global variables may be declared inside a {#link|struct#}, {#link|union#}, or {#link|enum#}:
< / p >
{#code_begin|test|namespaced_global#}
const std = @import("std");
const assert = std.debug.assert;
test "namespaced global variable" {
assert(foo() == 1235);
assert(foo() == 1236);
}
fn foo() i32 {
const S = struct {
var x: i32 = 1234;
};
S.x += 1;
return S.x;
}
{#code_end#}
< p >
The {#syntax#}extern{#endsyntax#} keyword can be used to link against a variable that is exported
from another object. The {#syntax#}export{#endsyntax#} keyword or {#link|@export#} builtin function
can be used to make a variable available to other objects at link time. In both cases,
the type of the variable must be C ABI compatible.
< / p >
{#see_also|Exporting a C Library#}
{#header_close#}
{#header_open|Thread Local Variables#}
< p > A variable may be specified to be a thread-local variable using the
{#syntax#}threadlocal{#endsyntax#} keyword:< / p >
{#code_begin|test|tls#}
const std = @import("std");
const assert = std.debug.assert;
threadlocal var x: i32 = 1234;
test "thread local storage" {
2019-05-27 04:35:26 +01:00
const thread1 = try std.Thread.spawn({}, testTls);
const thread2 = try std.Thread.spawn({}, testTls);
2019-04-04 17:26:47 +01:00
testTls({});
thread1.wait();
thread2.wait();
}
fn testTls(context: void) void {
assert(x == 1234);
x += 1;
assert(x == 1235);
}
{#code_end#}
< p >
For {#link|Single Threaded Builds#}, all thread local variables are treated as {#link|Global Variables#}.
< / p >
< p >
Thread local variables may not be {#syntax#}const{#endsyntax#}.
< / p >
{#header_close#}
{#header_open|Local Variables#}
< p >
Local variables occur inside {#link|Functions#}, {#link|comptime#} blocks, and {#link|@cImport#} blocks.
< / p >
< p >
When a local variable is {#syntax#}const{#endsyntax#}, it means that after initialization, the variable's
value will not change. If the initialization value of a {#syntax#}const{#endsyntax#} variable is
{#link|comptime#}-known, then the variable is also {#syntax#}comptime{#endsyntax#}-known.
< / p >
< p >
A local variable may be qualified with the {#syntax#}comptime{#endsyntax#} keyword. This causes
the variable's value to be {#syntax#}comptime{#endsyntax#}-known, and all loads and stores of the
variable to happen during semantic analysis of the program, rather than at runtime.
All variables declared in a {#syntax#}comptime{#endsyntax#} expression are implicitly
{#syntax#}comptime{#endsyntax#} variables.
< / p >
{#code_begin|test|comptime_vars#}
const std = @import("std");
const assert = std.debug.assert;
test "comptime vars" {
var x: i32 = 1;
comptime var y: i32 = 1;
x += 1;
y += 1;
assert(x == 2);
assert(y == 2);
if (y != 2) {
// This compile error never triggers because y is a comptime variable,
// and so `y != 2` is a comptime value, and this if is statically evaluated.
@compileError("wrong y value");
}
}
{#code_end#}
{#header_close#}
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|Integers#}
{#header_open|Integer Literals#}
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
const decimal_int = 98222;
2017-11-07 08:22:27 +00:00
const hex_int = 0xff;
const another_hex_int = 0xFF;
const octal_int = 0o755;
2018-01-19 08:03:20 +00:00
const binary_int = 0b11110000;
2020-03-15 01:37:36 +00:00
// underscores may be placed between two digits as a visual separator
const one_billion = 1_000_000_000;
const binary_mask = 0b1_1111_1111;
const permissions = 0o7_5_5;
const big_address = 0xFF80_0000_0000_0000;
2018-01-19 08:03:20 +00:00
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Runtime Integer Values#}
2017-11-07 08:22:27 +00:00
< p >
Integer literals have no size limitation, and if any undefined behavior occurs,
the compiler catches it.
< / p >
< p >
However, once an integer value is no longer known at compile-time, it must have a
known size, and is vulnerable to undefined behavior.
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
2018-01-25 09:10:11 +00:00
fn divide(a: i32, b: i32) i32 {
2017-11-07 08:22:27 +00:00
return a / b;
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
In this function, values {#syntax#}a{#endsyntax#} and {#syntax#}b{#endsyntax#} are known only at runtime,
2019-02-22 15:56:49 +00:00
and thus this division operation is vulnerable to both {#link|Integer Overflow#} and
{#link|Division by Zero#}.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2018-09-14 15:35:03 +01:00
Operators such as {#syntax#}+{#endsyntax#} and {#syntax#}-{#endsyntax#} cause undefined behavior on
integer overflow. Also available are operations such as {#syntax#}+%{#endsyntax#} and
{#syntax#}-%{#endsyntax#} which are defined to have wrapping arithmetic on all targets.
2017-11-07 08:22:27 +00:00
< / p >
2019-02-22 15:56:49 +00:00
< p >
Zig supports arbitrary bit-width integers, referenced by using
2019-12-05 21:38:59 +00:00
an identifier of < code > i< / code > or < code > u< / code > followed by digits. For example, the identifier
2019-02-22 15:56:49 +00:00
{#syntax#}i7{#endsyntax#} refers to a signed 7-bit integer. The maximum allowed bit-width of an
integer type is {#syntax#}65535{#endsyntax#}.
< / p >
{#see_also|Wrapping Operations#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_close#}
{#header_open|Floats#}
2018-06-17 00:53:52 +01:00
< p > Zig has the following floating point types:< / p >
< ul >
2018-09-14 15:35:03 +01:00
< li > {#syntax#}f16{#endsyntax#} - IEEE-754-2008 binary16< / li >
< li > {#syntax#}f32{#endsyntax#} - IEEE-754-2008 binary32< / li >
< li > {#syntax#}f64{#endsyntax#} - IEEE-754-2008 binary64< / li >
< li > {#syntax#}f128{#endsyntax#} - IEEE-754-2008 binary128< / li >
< li > {#syntax#}c_longdouble{#endsyntax#} - matches < code class = "c" > long double< / code > for the target C ABI< / li >
2018-06-17 00:53:52 +01:00
< / ul >
2018-01-17 04:19:05 +00:00
{#header_open|Float Literals#}
2018-06-17 00:53:52 +01:00
< p >
2019-03-23 19:25:38 +00:00
Float literals have type {#syntax#}comptime_float{#endsyntax#} which is guaranteed to have
the same precision and operations of the largest other floating point type, which is
{#syntax#}f128{#endsyntax#}.
< / p >
< p >
2019-11-08 20:56:21 +00:00
Float literals {#link|coerce|Type Coercion#} to any floating point type,
2019-03-23 19:25:38 +00:00
and to any {#link|integer|Integers#} type when there is no fractional component.
2018-06-17 00:53:52 +01:00
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
const floating_point = 123.0E+77;
2017-11-07 08:22:27 +00:00
const another_float = 123.0;
const yet_another = 123.0e+77;
const hex_floating_point = 0x103.70p-5;
const another_hex_float = 0x103.70;
2018-01-19 08:03:20 +00:00
const yet_another_hex_float = 0x103.70P-5;
2020-03-15 01:37:36 +00:00
// underscores may be placed between two digits as a visual separator
const lightspeed = 299_792_458.000_000;
const nanosecond = 0.000_000_001;
const more_hex = 0x1234_5678.9ABC_CDEFp-10;
2019-03-23 19:25:38 +00:00
{#code_end#}
< p >
There is no syntax for NaN, infinity, or negative infinity. For these special values,
one must use the standard library:
< / p >
{#code_begin|syntax#}
const std = @import("std");
const inf = std.math.inf(f32);
const negative_inf = -std.math.inf(f64);
const nan = std.math.nan(f128);
2018-01-19 08:03:20 +00:00
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Floating Point Operations#}
2018-09-14 15:35:03 +01:00
< p > By default floating point operations use {#syntax#}Strict{#endsyntax#} mode,
but you can switch to {#syntax#}Optimized{#endsyntax#} mode on a per-block basis:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|obj|foo#}
{#code_release_fast#}
2020-09-27 05:03:38 +01:00
{#code_disable_cache#}
2020-02-27 19:41:44 +00:00
const std = @import("std");
const builtin = std.builtin;
2019-11-08 20:56:21 +00:00
const big = @as(f64, 1 < < 40 ) ;
2017-11-07 08:22:27 +00:00
2018-01-25 09:10:11 +00:00
export fn foo_strict(x: f64) f64 {
2017-11-07 08:22:27 +00:00
return x + big - big;
}
2018-01-25 09:10:11 +00:00
export fn foo_optimized(x: f64) f64 {
2020-03-23 23:00:52 +00:00
@setFloatMode(.Optimized);
2017-11-07 08:22:27 +00:00
return x + big - big;
2018-01-19 08:03:20 +00:00
}
{#code_end#}
< p > 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.< / p >
{#code_begin|exe|float_mode#}
{#code_link_object|foo#}
2020-06-19 10:38:22 +01:00
const print = @import("std").debug.print;
2017-11-07 08:22:27 +00:00
2018-01-25 09:10:11 +00:00
extern fn foo_strict(x: f64) f64;
extern fn foo_optimized(x: f64) f64;
2017-11-07 08:22:27 +00:00
2018-02-08 08:02:41 +00:00
pub fn main() void {
2017-11-07 08:22:27 +00:00
const x = 0.001;
2020-06-19 10:38:22 +01:00
print("optimized = {}\n", .{foo_optimized(x)});
print("strict = {}\n", .{foo_strict(x)});
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-01-17 05:22:33 +00:00
{#see_also|@setFloatMode|Division by Zero#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-01-23 04:06:07 +00:00
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|Operators#}
2018-10-05 23:25:20 +01:00
< p >
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.
< / p >
2018-01-17 04:19:05 +00:00
{#header_open|Table of Operators#}
2018-01-30 04:33:38 +00:00
< div class = "table-wrapper" >
2017-11-07 08:22:27 +00:00
< table >
< tr >
< th >
Syntax
< / th >
< th >
Relevant Types
< / th >
< th >
Description
< / th >
< th >
Example
< / th >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a + b
a += b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
< li > {#link|Floats#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td > Addition.
< ul >
2018-01-23 04:06:07 +00:00
< li > Can cause {#link|overflow|Default Operations#} for integers.< / li >
2018-08-20 19:21:58 +01:00
< li > Invokes {#link|Peer Type Resolution#} for the operands.< / li >
< li > See also {#link|@addWithOverflow#}.< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}2 + 5 == 7{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a +% b
a +%= b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td > Wrapping Addition.
< ul >
< li > Guaranteed to have twos-complement wrapping behavior.< / li >
2018-08-20 19:21:58 +01:00
< li > Invokes {#link|Peer Type Resolution#} for the operands.< / li >
2018-08-07 06:10:29 +01:00
< li > See also {#link|@addWithOverflow#}.< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2019-12-03 10:56:50 +00:00
< pre > {#syntax#}@as(u32, std.math.maxInt(u32)) +% 1 == 0{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a - b
a -= b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
< li > {#link|Floats#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td > Subtraction.
< ul >
2018-01-23 04:06:07 +00:00
< li > Can cause {#link|overflow|Default Operations#} for integers.< / li >
2018-08-20 19:21:58 +01:00
< li > Invokes {#link|Peer Type Resolution#} for the operands.< / li >
< li > See also {#link|@subWithOverflow#}.< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}2 - 5 == -3{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a -% b
a -%= b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td > Wrapping Subtraction.
< ul >
< li > Guaranteed to have twos-complement wrapping behavior.< / li >
2018-08-20 19:21:58 +01:00
< li > Invokes {#link|Peer Type Resolution#} for the operands.< / li >
< li > See also {#link|@subWithOverflow#}.< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2019-12-03 10:56:50 +00:00
< pre > {#syntax#}@as(u32, 0) -% 1 == std.math.maxInt(u32){#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}-a{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
< li > {#link|Floats#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
Negation.
< ul >
2018-01-23 04:06:07 +00:00
< li > Can cause {#link|overflow|Default Operations#} for integers.< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}-1 == 0 - 1{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}-%a{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
Wrapping Negation.
< ul >
< li > Guaranteed to have twos-complement wrapping behavior.< / li >
< / ul >
< / td >
< td >
2019-12-03 10:56:50 +00:00
< pre > {#syntax#}-%@as(i32, std.math.minInt(i32)) == std.math.minInt(i32){#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a * b
a *= b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
< li > {#link|Floats#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td > Multiplication.
< ul >
2018-01-23 04:06:07 +00:00
< li > Can cause {#link|overflow|Default Operations#} for integers.< / li >
2018-08-20 19:21:58 +01:00
< li > Invokes {#link|Peer Type Resolution#} for the operands.< / li >
< li > See also {#link|@mulWithOverflow#}.< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}2 * 5 == 10{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a *% b
a *%= b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td > Wrapping Multiplication.
< ul >
< li > Guaranteed to have twos-complement wrapping behavior.< / li >
2018-08-20 19:21:58 +01:00
< li > Invokes {#link|Peer Type Resolution#} for the operands.< / li >
< li > See also {#link|@mulWithOverflow#}.< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2019-12-03 10:56:50 +00:00
< pre > {#syntax#}@as(u8, 200) *% 2 == 144{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a / b
a /= b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
< li > {#link|Floats#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
2018-11-16 18:33:58 +00:00
< td > Division.
2017-11-07 08:22:27 +00:00
< ul >
2018-01-23 04:06:07 +00:00
< li > Can cause {#link|overflow|Default Operations#} for integers.< / li >
< li > Can cause {#link|Division by Zero#} for integers.< / li >
< li > Can cause {#link|Division by Zero#} for floats in {#link|FloatMode.Optimized Mode|Floating Point Operations#}.< / li >
2017-11-07 08:22:27 +00:00
< li > For non-compile-time-known signed integers, must use
2018-01-23 04:06:07 +00:00
{#link|@divTrunc#},
{#link|@divFloor#}, or
2018-09-14 15:35:03 +01:00
{#link|@divExact#} instead of {#syntax#}/{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / li >
2018-08-20 19:21:58 +01:00
< li > Invokes {#link|Peer Type Resolution#} for the operands.< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}10 / 5 == 2{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a % b
a %= b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
< li > {#link|Floats#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td > Remainder Division.
< ul >
2018-01-23 04:06:07 +00:00
< li > Can cause {#link|Division by Zero#} for integers.< / li >
< li > Can cause {#link|Division by Zero#} for floats in {#link|FloatMode.Optimized Mode|Floating Point Operations#}.< / li >
2017-11-07 08:22:27 +00:00
< li > For non-compile-time-known signed integers, must use
2018-01-23 04:06:07 +00:00
{#link|@rem#} or
2018-09-14 15:35:03 +01:00
{#link|@mod#} instead of {#syntax#}%{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / li >
2018-08-20 19:21:58 +01:00
< li > Invokes {#link|Peer Type Resolution#} for the operands.< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}10 % 3 == 1{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a < < b
a < < = b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td > Bit Shift Left.
< ul >
2018-09-14 15:35:03 +01:00
< li > {#syntax#}b{#endsyntax#} must be {#link|comptime-known|comptime#} or have a type with log2 number of bits as {#syntax#}a{#endsyntax#}.< / li >
2018-01-23 04:06:07 +00:00
< li > See also {#link|@shlExact#}.< / li >
< li > See also {#link|@shlWithOverflow#}.< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}1 < < 8 = = 256 { # endsyntax # } < / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a >> b
a >>= b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td > Bit Shift Right.
< ul >
2018-09-14 15:35:03 +01:00
< li > {#syntax#}b{#endsyntax#} must be {#link|comptime-known|comptime#} or have a type with log2 number of bits as {#syntax#}a{#endsyntax#}.< / li >
2018-01-23 04:06:07 +00:00
< li > See also {#link|@shrExact#}.< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}10 >> 1 == 5{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a & b
a & = b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td > Bitwise AND.
2018-08-20 19:21:58 +01:00
< ul >
< li > Invokes {#link|Peer Type Resolution#} for the operands.< / li >
< / ul >
2017-11-07 08:22:27 +00:00
< / td >
< td >
2018-10-05 15:21:08 +01:00
< pre > {#syntax#}0b011 & 0b101 == 0b001{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a | b
a |= b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td > Bitwise OR.
2018-08-20 19:21:58 +01:00
< ul >
< li > Invokes {#link|Peer Type Resolution#} for the operands.< / li >
< / ul >
2017-11-07 08:22:27 +00:00
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}0b010 | 0b100 == 0b110{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a ^ b
a ^= b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td > Bitwise XOR.
2018-08-20 19:21:58 +01:00
< ul >
< li > Invokes {#link|Peer Type Resolution#} for the operands.< / li >
< / ul >
2017-11-07 08:22:27 +00:00
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}0b011 ^ 0b101 == 0b110{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}~a{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
Bitwise NOT.
< / td >
< td >
2019-12-03 10:56:50 +00:00
< pre > {#syntax#}~@as(u8, 0b10101111) == 0b01010000{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a orelse b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-06-10 04:42:14 +01:00
< li > {#link|Optionals#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
2018-09-14 15:35:03 +01:00
< td > If {#syntax#}a{#endsyntax#} is {#syntax#}null{#endsyntax#},
returns {#syntax#}b{#endsyntax#} ("default value"),
otherwise returns the unwrapped value of {#syntax#}a{#endsyntax#}.
Note that {#syntax#}b{#endsyntax#} may be a value of type {#link|noreturn#}.
2017-11-07 08:22:27 +00:00
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}const value: ?u32 = null;
2018-06-10 06:13:51 +01:00
const unwrapped = value orelse 1234;
2018-09-14 15:35:03 +01:00
unwrapped == 1234{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a.?{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-06-10 04:42:14 +01:00
< li > {#link|Optionals#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
Equivalent to:
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}a orelse unreachable{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}const value: ?u32 = 5678;
value.? == 5678{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a catch b
a catch |err| b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Error Unions|Errors#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
2018-11-13 13:08:37 +00:00
< td > If {#syntax#}a{#endsyntax#} is an {#syntax#}error{#endsyntax#},
2018-09-14 15:35:03 +01:00
returns {#syntax#}b{#endsyntax#} ("default value"),
otherwise returns the unwrapped value of {#syntax#}a{#endsyntax#}.
Note that {#syntax#}b{#endsyntax#} may be a value of type {#link|noreturn#}.
2018-11-13 13:08:37 +00:00
{#syntax#}err{#endsyntax#} is the {#syntax#}error{#endsyntax#} and is in scope of the expression {#syntax#}b{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / td >
< td >
2018-11-13 13:08:37 +00:00
< pre > {#syntax#}const value: anyerror!u32 = error.Broken;
2018-01-07 22:28:20 +00:00
const unwrapped = value catch 1234;
2018-09-14 15:35:03 +01:00
unwrapped == 1234{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a and b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|bool|Primitive Types#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
If {#syntax#}a{#endsyntax#} is {#syntax#}false{#endsyntax#}, returns {#syntax#}false{#endsyntax#}
without evaluating {#syntax#}b{#endsyntax#}. Otherwise, returns {#syntax#}b{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / td >
< td >
2019-09-22 16:13:36 +01:00
< pre > {#syntax#}(false and true) == false{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a or b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|bool|Primitive Types#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
If {#syntax#}a{#endsyntax#} is {#syntax#}true{#endsyntax#}, returns {#syntax#}true{#endsyntax#}
without evaluating {#syntax#}b{#endsyntax#}. Otherwise, returns {#syntax#}b{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}false or true == true{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}!a{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|bool|Primitive Types#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
Boolean NOT.
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}!false == true{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a == b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
< li > {#link|Floats#}< / li >
< li > {#link|bool|Primitive Types#}< / li >
< li > {#link|type|Primitive Types#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
Returns {#syntax#}true{#endsyntax#} if a and b are equal, otherwise returns {#syntax#}false{#endsyntax#}.
2018-08-20 19:21:58 +01:00
Invokes {#link|Peer Type Resolution#} for the operands.
2017-11-07 08:22:27 +00:00
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}(1 == 1) == true{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a == null{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-06-10 04:42:14 +01:00
< li > {#link|Optionals#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
Returns {#syntax#}true{#endsyntax#} if a is {#syntax#}null{#endsyntax#}, otherwise returns {#syntax#}false{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}const value: ?u32 = null;
value == null{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a != b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
< li > {#link|Floats#}< / li >
< li > {#link|bool|Primitive Types#}< / li >
< li > {#link|type|Primitive Types#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
Returns {#syntax#}false{#endsyntax#} if a and b are equal, otherwise returns {#syntax#}true{#endsyntax#}.
2018-08-20 19:21:58 +01:00
Invokes {#link|Peer Type Resolution#} for the operands.
2017-11-07 08:22:27 +00:00
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}(1 != 1) == false{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a > b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
< li > {#link|Floats#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
Returns {#syntax#}true{#endsyntax#} if a is greater than b, otherwise returns {#syntax#}false{#endsyntax#}.
2018-08-20 19:21:58 +01:00
Invokes {#link|Peer Type Resolution#} for the operands.
2017-11-07 08:22:27 +00:00
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}(2 > 1) == true{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a >= b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
< li > {#link|Floats#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
Returns {#syntax#}true{#endsyntax#} if a is greater than or equal to b, otherwise returns {#syntax#}false{#endsyntax#}.
2018-08-20 19:21:58 +01:00
Invokes {#link|Peer Type Resolution#} for the operands.
2017-11-07 08:22:27 +00:00
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}(2 >= 1) == true{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a < b { # endsyntax # } < / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
< li > {#link|Floats#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
Returns {#syntax#}true{#endsyntax#} if a is less than b, otherwise returns {#syntax#}false{#endsyntax#}.
2018-08-20 19:21:58 +01:00
Invokes {#link|Peer Type Resolution#} for the operands.
2017-11-07 08:22:27 +00:00
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}(1 < 2 ) = = true { # endsyntax # } > < / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a < = b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Integers#}< / li >
< li > {#link|Floats#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
Returns {#syntax#}true{#endsyntax#} if a is less than or equal to b, otherwise returns {#syntax#}false{#endsyntax#}.
2018-08-20 19:21:58 +01:00
Invokes {#link|Peer Type Resolution#} for the operands.
2017-11-07 08:22:27 +00:00
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}(1 < = 2) == true{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a ++ b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Arrays#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
Array concatenation.
< ul >
2018-09-14 15:35:03 +01:00
< li > Only available when {#syntax#}a{#endsyntax#} and {#syntax#}b{#endsyntax#} are {#link|compile-time known|comptime#}.
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}const mem = @import("std").mem;
2019-06-10 00:24:24 +01:00
const array1 = [_]u32{1,2};
const array2 = [_]u32{3,4};
2017-11-07 08:22:27 +00:00
const together = array1 ++ array2;
2020-05-10 13:35:21 +01:00
mem.eql(u32, & together, & [_]u32{1,2,3,4}){#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a ** b{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Arrays#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
Array multiplication.
< ul >
2018-09-14 15:35:03 +01:00
< li > Only available when {#syntax#}a{#endsyntax#} and {#syntax#}b{#endsyntax#} are {#link|compile-time known|comptime#}.
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}const mem = @import("std").mem;
2017-11-07 08:22:27 +00:00
const pattern = "ab" ** 3;
2018-09-14 15:35:03 +01:00
mem.eql(u8, pattern, "ababab"){#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a.*{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Pointers#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
Pointer dereference.
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}const x: u32 = 1234;
const ptr = &x;
2019-03-22 17:57:00 +00:00
ptr.* == 1234{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-10-05 15:21:08 +01:00
< td > < pre > {#syntax#}& a{#endsyntax#}< / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
All types
< / td >
< td >
Address of.
< / td >
< td >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}const x: u32 = 1234;
const ptr = &x;
2019-03-22 17:57:00 +00:00
ptr.* == 1234{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
2018-06-13 16:09:41 +01:00
< tr >
2018-09-14 15:35:03 +01:00
< td > < pre > {#syntax#}a || b{#endsyntax#}< / pre > < / td >
2018-06-13 16:09:41 +01:00
< td >
< ul >
< li > {#link|Error Set Type#}< / li >
< / ul >
< / td >
< td >
{#link|Merging Error Sets#}
< / td >
< td >
2018-11-13 13:08:37 +00:00
< pre > {#syntax#}const A = error{One};
const B = error{Two};
(A || B) == error{One, Two}{#endsyntax#}< / pre >
2018-06-13 16:09:41 +01:00
< / td >
< / tr >
2017-11-07 08:22:27 +00:00
< / table >
2018-01-30 04:33:38 +00:00
< / div >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Precedence#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}x() x[] x.y
2018-02-08 08:02:41 +00:00
a!b
2018-09-14 15:35:03 +01:00
!x -x -%x ~x & x ?x
2018-06-10 04:42:14 +01:00
x{} x.* x.?
2018-06-13 16:09:41 +01:00
! * / % ** *% ||
2017-11-07 08:22:27 +00:00
+ - ++ +% -%
2018-09-14 15:35:03 +01:00
< < >>
2020-04-08 21:58:01 +01:00
& ^ |
2018-09-14 15:35:03 +01:00
== != < > < = >=
2017-11-07 08:22:27 +00:00
and
or
2018-06-10 06:13:51 +01:00
orelse catch
2018-09-14 15:35:03 +01:00
= *= /= %= += -= < < = >>= & = ^= |={#endsyntax#}< / pre >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_close#}
{#header_open|Arrays#}
2018-01-19 08:03:20 +00:00
{#code_begin|test|arrays#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
const mem = @import("std").mem;
// array literal
2019-06-10 00:24:24 +01:00
const message = [_]u8{ 'h', 'e', 'l', 'l', 'o' };
2017-11-07 08:22:27 +00:00
// get the size of an array
comptime {
assert(message.len == 5);
}
2019-11-20 22:11:07 +00:00
// A string literal is a pointer to an array literal.
2019-12-02 02:27:55 +00:00
const same_message = "hello";
2017-11-07 08:22:27 +00:00
comptime {
2019-12-02 02:27:55 +00:00
assert(mem.eql(u8, & message, same_message));
2017-11-07 08:22:27 +00:00
}
test "iterate over an array" {
var sum: usize = 0;
for (message) |byte| {
sum += byte;
}
2019-11-08 20:56:21 +00:00
assert(sum == 'h' + 'e' + 'l' * 2 + 'o');
2017-11-07 08:22:27 +00:00
}
// modifiable array
var some_integers: [100]i32 = undefined;
test "modify an array" {
for (some_integers) |*item, i| {
2018-06-17 07:57:07 +01:00
item.* = @intCast(i32, i);
2017-11-07 08:22:27 +00:00
}
assert(some_integers[10] == 10);
assert(some_integers[99] == 99);
}
// array concatenation works if the values are known
// at compile time
2019-06-10 00:24:24 +01:00
const part_one = [_]i32{ 1, 2, 3, 4 };
const part_two = [_]i32{ 5, 6, 7, 8 };
2017-11-07 08:22:27 +00:00
const all_of_it = part_one ++ part_two;
comptime {
2019-12-02 02:27:55 +00:00
assert(mem.eql(i32, & all_of_it, & [_]i32{ 1, 2, 3, 4, 5, 6, 7, 8 }));
2017-11-07 08:22:27 +00:00
}
// remember that string literals are arrays
const hello = "hello";
const world = "world";
const hello_world = hello ++ " " ++ world;
comptime {
assert(mem.eql(u8, hello_world, "hello world"));
}
// ** does repeating patterns
const pattern = "ab" ** 3;
comptime {
assert(mem.eql(u8, pattern, "ababab"));
}
// initialize an array to zero
2019-06-10 00:24:24 +01:00
const all_zero = [_]u16{0} ** 10;
2017-11-07 08:22:27 +00:00
comptime {
assert(all_zero.len == 10);
assert(all_zero[5] == 0);
}
// use compile-time code to initialize an array
2018-01-19 08:03:20 +00:00
var fancy_array = init: {
2017-11-07 08:22:27 +00:00
var initial_value: [10]Point = undefined;
for (initial_value) |*pt, i| {
2018-11-13 13:08:37 +00:00
pt.* = Point{
2018-06-17 07:57:07 +01:00
.x = @intCast(i32, i),
.y = @intCast(i32, i) * 2,
2017-11-07 08:22:27 +00:00
};
}
2018-01-19 08:03:20 +00:00
break :init initial_value;
2017-11-07 08:22:27 +00:00
};
2018-11-13 13:08:37 +00:00
const Point = struct {
2017-11-07 08:22:27 +00:00
x: i32,
y: i32,
};
2020-09-24 14:14:57 +01:00
test "compile-time array initialization" {
2017-11-07 08:22:27 +00:00
assert(fancy_array[4].x == 4);
assert(fancy_array[4].y == 8);
}
// call a function to initialize an array
2019-06-10 00:24:24 +01:00
var more_points = [_]Point{makePoint(3)} ** 10;
2018-01-25 09:10:11 +00:00
fn makePoint(x: i32) Point {
2018-11-13 13:08:37 +00:00
return Point{
2017-11-07 08:22:27 +00:00
.x = x,
.y = x * 2,
2018-01-19 08:03:20 +00:00
};
2017-11-07 08:22:27 +00:00
}
test "array initialization with function calls" {
assert(more_points[4].x == 3);
assert(more_points[4].y == 6);
assert(more_points.len == 10);
2018-01-19 08:03:20 +00:00
}
2019-07-16 18:13:21 +01:00
{#code_end#}
{#see_also|for|Slices#}
2019-07-15 23:20:56 +01:00
2019-11-12 00:57:57 +00:00
{#header_open|Anonymous List Literals#}
< p > Similar to {#link|Enum Literals#} and {#link|Anonymous Struct Literals#}
the type can be omitted from array literals:< / p >
{#code_begin|test|anon_list#}
const std = @import("std");
const assert = std.debug.assert;
test "anonymous list literal syntax" {
var array: [4]u8 = .{11, 22, 33, 44};
assert(array[0] == 11);
assert(array[1] == 22);
assert(array[2] == 33);
assert(array[3] == 44);
}
{#code_end#}
< p >
If there is no type in the result location then an anonymous list literal actually
turns into a {#link|struct#} with numbered field names:
< / p >
{#code_begin|test|infer_list_literal#}
const std = @import("std");
const assert = std.debug.assert;
test "fully anonymous list literal" {
dump(.{ @as(u32, 1234), @as(f64, 12.34), true, "hi"});
}
2020-07-11 12:08:20 +01:00
fn dump(args: anytype) void {
2019-11-12 00:57:57 +00:00
assert(args.@"0" == 1234);
assert(args.@"1" == 12.34);
assert(args.@"2");
assert(args.@"3"[0] == 'h');
assert(args.@"3"[1] == 'i');
}
{#code_end#}
{#header_close#}
2019-07-16 18:13:21 +01:00
{#header_open|Multidimensional Arrays#}
< p >
Mutlidimensional arrays can be created by nesting arrays:
< / p >
{#code_begin|test|multidimensional#}
const std = @import("std");
const assert = std.debug.assert;
const mat4x4 = [4][4]f32{
[_]f32{ 1.0, 0.0, 0.0, 0.0 },
[_]f32{ 0.0, 1.0, 0.0, 1.0 },
[_]f32{ 0.0, 0.0, 1.0, 0.0 },
[_]f32{ 0.0, 0.0, 0.0, 1.0 },
2019-07-15 23:20:56 +01:00
};
test "multidimensional arrays" {
2019-07-16 18:13:21 +01:00
// Access the 2D array by indexing the outer array, and then the inner array.
2019-07-15 23:20:56 +01:00
assert(mat4x4[1][1] == 1.0);
2019-07-16 18:13:21 +01:00
// Here we iterate with for loops.
for (mat4x4) |row, row_index| {
for (row) |cell, column_index| {
if (row_index == column_index) {
assert(cell == 1.0);
2019-07-15 23:20:56 +01:00
}
}
}
}
2018-01-19 08:03:20 +00:00
{#code_end#}
2019-07-16 18:13:21 +01:00
{#header_close#}
2019-11-20 22:11:07 +00:00
2019-11-24 03:29:12 +00:00
{#header_open|Sentinel-Terminated Arrays#}
2019-11-20 22:11:07 +00:00
< p >
2020-01-11 21:59:19 +00:00
The syntax {#syntax#}[N:x]T{#endsyntax#} describes an array which has a sentinel element of value {#syntax#}x{#endsyntax#} at the
2019-11-20 22:11:07 +00:00
index corresponding to {#syntax#}len{#endsyntax#}.
< / p >
{#code_begin|test|null_terminated_array#}
const std = @import("std");
const assert = std.debug.assert;
test "null terminated array" {
2019-11-24 03:29:12 +00:00
const array = [_:0]u8 {1, 2, 3, 4};
2019-11-20 22:11:07 +00:00
2019-12-09 20:59:42 +00:00
assert(@TypeOf(array) == [4:0]u8);
2019-11-20 22:11:07 +00:00
assert(array.len == 4);
2019-11-24 07:14:21 +00:00
assert(array[4] == 0);
2019-11-20 22:11:07 +00:00
}
{#code_end#}
2019-11-24 03:29:12 +00:00
{#see_also|Sentinel-Terminated Pointers|Sentinel-Terminated Slices#}
2019-11-20 22:11:07 +00:00
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2019-01-31 04:36:52 +00:00
{#header_open|Vectors#}
< p >
2020-07-16 06:26:43 +01:00
A vector is a group of booleans, {#link|Integers#}, {#link|Floats#}, or {#link|Pointers#} which are operated on
2020-04-28 06:46:49 +01:00
in parallel using a single instruction ({#link|SIMD#}). Vector types are created with the builtin function {#link|@Type#},
or using the shorthand as {#syntax#}std.meta.Vector{#endsyntax#}.
2019-01-31 04:36:52 +00:00
< / p >
< p >
TODO talk about C ABI interop
< / p >
{#header_open|SIMD#}
< p >
TODO Zig's SIMD abilities are just beginning to be fleshed out. Here are some talking points to update the
docs with:
* What kind of operations can you do? All the operations on integers and floats? What about mixing scalar and vector?
* How to convert to/from vectors/arrays
* How to access individual elements from vectors, how to loop over the elements
* "shuffle"
* Advice on writing high perf software, how to abstract the best way
< / p >
{#header_close#}
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|Pointers#}
2018-10-05 03:51:36 +01:00
< p >
Zig has two kinds of pointers:
< / p >
< ul >
< li > {#syntax#}*T{#endsyntax#} - pointer to exactly one item.
< ul >
< li > Supports deref syntax: {#syntax#}ptr.*{#endsyntax#}< / li >
< / ul >
< / li >
< li > {#syntax#}[*]T{#endsyntax#} - pointer to unknown number of items.
< ul >
< li > Supports index syntax: {#syntax#}ptr[i]{#endsyntax#}< / li >
< li > Supports slice syntax: {#syntax#}ptr[start..end]{#endsyntax#}< / li >
< li > Supports pointer arithmetic: {#syntax#}ptr + x{#endsyntax#}, {#syntax#}ptr - x{#endsyntax#}< / li >
< li > {#syntax#}T{#endsyntax#} must have a known size, which means that it cannot be
2020-09-26 16:05:11 +01:00
{#syntax#}c_void{#endsyntax#} or any other {#link|opaque type|opaque#}.< / li >
2018-10-05 03:51:36 +01:00
< / ul >
< / li >
< / ul >
< p > These types are closely related to {#link|Arrays#} and {#link|Slices#}:< / p >
< ul >
< li > {#syntax#}*[N]T{#endsyntax#} - pointer to N items, same as single-item pointer to array.
< ul >
< li > Supports index syntax: {#syntax#}array_ptr[i]{#endsyntax#}< / li >
< li > Supports slice syntax: {#syntax#}array_ptr[start..end]{#endsyntax#}< / li >
< li > Supports len property: {#syntax#}array_ptr.len{#endsyntax#}< / li >
< / ul >
< / li >
< / ul >
< ul >
< li > {#syntax#}[]T{#endsyntax#} - pointer to runtime-known number of items.
< ul >
< li > Supports index syntax: {#syntax#}slice[i]{#endsyntax#}< / li >
< li > Supports slice syntax: {#syntax#}slice[start..end]{#endsyntax#}< / li >
< li > Supports len property: {#syntax#}slice.len{#endsyntax#}< / li >
< / ul >
< / li >
< / ul >
< p > Use {#syntax#}& x{#endsyntax#} to obtain a single-item pointer:< / p >
{#code_begin|test#}
2018-01-19 08:03:20 +00:00
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
test "address of syntax" {
// Get the address of a variable:
const x: i32 = 1234;
const x_ptr = &x;
2019-03-22 17:57:00 +00:00
// Dereference a pointer:
2018-05-18 04:21:44 +01:00
assert(x_ptr.* == 1234);
2017-11-07 08:22:27 +00:00
2018-10-05 03:51:36 +01:00
// When you get the address of a const variable, you get a const pointer to a single item.
2019-12-09 20:59:42 +00:00
assert(@TypeOf(x_ptr) == *const i32);
2017-11-07 08:22:27 +00:00
// If you want to mutate the value, you'd need an address of a mutable variable:
var y: i32 = 5678;
const y_ptr = &y;
2019-12-09 20:59:42 +00:00
assert(@TypeOf(y_ptr) == *i32);
2018-05-18 04:21:44 +01:00
y_ptr.* += 1;
assert(y_ptr.* == 5679);
2017-11-07 08:22:27 +00:00
}
test "pointer array access" {
2018-06-04 06:09:15 +01:00
// Taking an address of an individual element gives a
// pointer to a single item. This kind of pointer
// does not support pointer arithmetic.
2019-06-10 00:24:24 +01:00
var array = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
2018-06-04 06:09:15 +01:00
const ptr = &array[2];
2019-12-09 20:59:42 +00:00
assert(@TypeOf(ptr) == *u8);
2017-11-07 08:22:27 +00:00
assert(array[2] == 3);
2018-06-04 06:09:15 +01:00
ptr.* += 1;
2017-11-07 08:22:27 +00:00
assert(array[2] == 4);
}
2018-10-05 03:51:36 +01:00
{#code_end#}
< p >
2019-11-24 03:29:12 +00:00
In Zig, we generally prefer {#link|Slices#} rather than {#link|Sentinel-Terminated Pointers#}.
2018-10-05 03:51:36 +01:00
You can turn an array or pointer into a slice using slice syntax.
< / p >
< p >
Slices have bounds checking and are therefore protected
against this kind of undefined behavior. This is one reason
we prefer slices to pointers.
< / p >
{#code_begin|test#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
test "pointer slicing" {
2019-06-10 00:24:24 +01:00
var array = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
2018-06-04 06:09:15 +01:00
const slice = array[2..4];
2017-11-07 08:22:27 +00:00
assert(slice.len == 2);
assert(array[3] == 4);
slice[1] += 1;
assert(array[3] == 5);
}
2018-10-05 03:51:36 +01:00
{#code_end#}
2019-02-22 15:56:49 +00:00
< p > Pointers work at compile-time too, as long as the code does not depend on
2018-10-05 03:51:36 +01:00
an undefined memory layout:< / p >
{#code_begin|test#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
2018-10-05 03:51:36 +01:00
test "comptime pointers" {
comptime {
var x: i32 = 1;
const ptr = &x;
ptr.* += 1;
x += 1;
assert(ptr.* == 3);
}
2017-11-07 08:22:27 +00:00
}
2018-10-05 03:51:36 +01:00
{#code_end#}
< p > To convert an integer address into a pointer, use {#syntax#}@intToPtr{#endsyntax#}.
To convert a pointer to an integer, use {#syntax#}@ptrToInt{#endsyntax#}:< / p >
{#code_begin|test#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
test "@ptrToInt and @intToPtr" {
2019-12-15 11:48:35 +00:00
const ptr = @intToPtr(*i32, 0xdeadbee0);
2017-11-07 08:22:27 +00:00
const addr = @ptrToInt(ptr);
2019-12-09 20:59:42 +00:00
assert(@TypeOf(addr) == usize);
2019-12-15 11:48:35 +00:00
assert(addr == 0xdeadbee0);
2017-11-07 08:22:27 +00:00
}
2018-10-05 03:51:36 +01:00
{#code_end#}
< p > Zig is able to preserve memory addresses in comptime code, as long as
the pointer is never dereferenced:< / p >
{#code_begin|test#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
2018-10-05 03:51:36 +01:00
test "comptime @intToPtr" {
comptime {
// Zig is able to do this at compile-time, as long as
// ptr is never dereferenced.
2019-12-15 11:48:35 +00:00
const ptr = @intToPtr(*i32, 0xdeadbee0);
2018-10-05 03:51:36 +01:00
const addr = @ptrToInt(ptr);
2019-12-09 20:59:42 +00:00
assert(@TypeOf(addr) == usize);
2019-12-15 11:48:35 +00:00
assert(addr == 0xdeadbee0);
2018-10-05 03:51:36 +01:00
}
2017-11-07 08:22:27 +00:00
}
2018-10-05 03:51:36 +01:00
{#code_end#}
2019-03-25 16:55:45 +00:00
{#see_also|Optional Pointers|@intToPtr|@ptrToInt|C Pointers|Pointers to Zero Bit Types#}
2018-10-05 03:51:36 +01:00
{#header_open|volatile#}
< p > Loads and stores are assumed to not have side effects. If a given load or store
should have side effects, such as Memory Mapped Input/Output (MMIO), use {#syntax#}volatile{#endsyntax#}.
In the following code, loads and stores with {#syntax#}mmio_ptr{#endsyntax#} are guaranteed to all happen
and in the same order as in source code:< / p >
{#code_begin|test#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
test "volatile" {
2018-05-31 15:56:59 +01:00
const mmio_ptr = @intToPtr(*volatile u8, 0x12345678);
2019-12-09 20:59:42 +00:00
assert(@TypeOf(mmio_ptr) == *volatile u8);
2017-11-07 08:22:27 +00:00
}
2018-10-05 03:51:36 +01:00
{#code_end#}
< p >
Note that {#syntax#}volatile{#endsyntax#} is unrelated to concurrency and {#link|Atomics#}.
If you see code that is using {#syntax#}volatile{#endsyntax#} for something other than Memory Mapped
Input/Output, it is probably a bug.
< / p >
{#header_close#}
< p >
To convert one pointer type to another, use {#link|@ptrCast#}. This is an unsafe
operation that Zig cannot protect you against. Use {#syntax#}@ptrCast{#endsyntax#} only when other
conversions are not possible.
< / p >
{#code_begin|test#}
2020-02-23 17:03:50 +00:00
const std = @import("std");
const assert = std.debug.assert;
2017-11-07 08:22:27 +00:00
test "pointer casting" {
2019-06-10 00:24:24 +01:00
const bytes align(@alignOf(u32)) = [_]u8{ 0x12, 0x12, 0x12, 0x12 };
2018-09-05 20:53:36 +01:00
const u32_ptr = @ptrCast(*const u32, &bytes);
2018-05-18 04:21:44 +01:00
assert(u32_ptr.* == 0x12121212);
2017-11-07 08:22:27 +00:00
// Even this example is contrived - there are better ways to do the above than
// pointer casting. For example, using a slice narrowing cast:
2020-02-23 17:03:50 +00:00
const u32_value = std.mem.bytesAsSlice(u32, bytes[0..])[0];
2017-11-07 08:22:27 +00:00
assert(u32_value == 0x12121212);
// And even another way, the most straightforward way to do it:
assert(@bitCast(u32, bytes) == 0x12121212);
}
test "pointer child type" {
// pointer types have a `child` field which tells you the type they point to.
2020-09-04 20:49:14 +01:00
assert(@typeInfo(*u32).Pointer.child == u32);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_open|Alignment#}
2017-11-07 08:22:27 +00:00
< p >
Each type has an < strong > alignment< / strong > - 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
2018-01-23 04:06:07 +00:00
{#link|@alignOf#} to find out this value for any type.
2017-11-07 08:22:27 +00:00
< / p >
< p >
Alignment depends on the CPU architecture, but is always a power of two, and
2018-09-14 15:35:03 +01:00
less than {#syntax#}1 < < 29 { # endsyntax # } .
2017-11-07 08:22:27 +00:00
< / p >
< p >
In Zig, a pointer type has an alignment value. If the value is equal to the
alignment of the underlying type, it can be omitted from the type:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
2020-02-27 19:41:44 +00:00
const std = @import("std");
const assert = std.debug.assert;
2017-11-07 08:22:27 +00:00
test "variable alignment" {
var x: i32 = 1234;
2019-12-09 20:59:42 +00:00
const align_of_i32 = @alignOf(@TypeOf(x));
assert(@TypeOf(& x) == *i32);
2018-05-31 15:56:59 +01:00
assert(*i32 == *align(align_of_i32) i32);
2020-02-27 19:41:44 +00:00
if (std.Target.current.cpu.arch == .x86_64) {
2020-09-04 20:49:14 +01:00
assert(@typeInfo(*i32).Pointer.alignment == 4);
2017-11-07 08:22:27 +00:00
}
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2019-11-08 20:56:21 +00:00
< p > In the same way that a {#syntax#}*i32{#endsyntax#} can be {#link|coerced|Type Coercion#} to a
2018-09-14 15:35:03 +01:00
{#syntax#}*const i32{#endsyntax#}, a pointer with a larger alignment can be implicitly
2017-11-07 08:22:27 +00:00
cast to a pointer with a smaller alignment, but not vice versa.
< / p >
< p >
You can specify alignment on variables and functions. If you do this, then
pointers to them get the specified alignment:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
var foo: u8 align(4) = 100;
test "global variable alignment" {
2020-09-04 20:49:14 +01:00
assert(@typeInfo(@TypeOf(& foo)).Pointer.alignment == 4);
2019-12-09 20:59:42 +00:00
assert(@TypeOf(& foo) == *align(4) u8);
2020-03-19 01:25:35 +00:00
const as_pointer_to_array: *[1]u8 = &foo;
const as_slice: []u8 = as_pointer_to_array;
assert(@TypeOf(as_slice) == []align(4) u8);
2017-11-07 08:22:27 +00:00
}
2018-01-25 09:10:11 +00:00
fn derp() align(@sizeOf(usize) * 2) i32 { return 1234; }
fn noop1() align(1) void {}
fn noop4() align(4) void {}
2017-11-07 08:22:27 +00:00
test "function alignment" {
assert(derp() == 1234);
2019-12-09 20:59:42 +00:00
assert(@TypeOf(noop1) == fn() align(1) void);
assert(@TypeOf(noop4) == fn() align(4) void);
2017-11-07 08:22:27 +00:00
noop1();
noop4();
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
If you have a pointer or a slice that has a small alignment, but you know that it actually
2018-01-23 04:06:07 +00:00
has a bigger alignment, use {#link|@alignCast#} to change the
2017-11-07 08:22:27 +00:00
pointer into a more aligned pointer. This is a no-op at runtime, but inserts a
2018-01-23 04:06:07 +00:00
{#link|safety check|Incorrect Pointer Alignment#}:
2017-11-07 08:22:27 +00:00
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_safety|incorrect alignment#}
2020-02-23 17:03:50 +00:00
const std = @import("std");
2017-11-07 08:22:27 +00:00
test "pointer alignment safety" {
2019-06-10 00:24:24 +01:00
var array align(4) = [_]u32{ 0x11111111, 0x11111111 };
2020-02-23 17:03:50 +00:00
const bytes = std.mem.sliceAsBytes(array[0..]);
std.debug.assert(foo(bytes) == 0x11111111);
2017-11-07 08:22:27 +00:00
}
2018-01-25 09:10:11 +00:00
fn foo(bytes: []u8) u32 {
2017-11-07 08:22:27 +00:00
const slice4 = bytes[1..5];
2020-02-23 17:03:50 +00:00
const int_slice = std.mem.bytesAsSlice(u32, @alignCast(4, slice4));
2017-11-07 08:22:27 +00:00
return int_slice[0];
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2019-03-25 16:55:45 +00:00
{#header_open|allowzero#}
< p >
This pointer attribute allows a pointer to have address zero. This is only ever needed on the
2019-05-31 03:38:26 +01:00
freestanding OS target, where the address zero is mappable. If you want to represent null pointers, use
2019-12-17 04:55:35 +00:00
{#link|Optional Pointers#} instead. {#link|Optional Pointers#} with {#syntax#}allowzero{#endsyntax#}
are not the same size as pointers. In this code example, if the pointer
did not have the {#syntax#}allowzero{#endsyntax#} attribute, this would be a
{#link|Pointer Cast Invalid Null#} panic:
2019-03-25 16:55:45 +00:00
< / p >
{#code_begin|test|allowzero#}
const std = @import("std");
const assert = std.debug.assert;
test "allowzero" {
var zero: usize = 0;
var ptr = @intToPtr(*allowzero i32, zero);
assert(@ptrToInt(ptr) == 0);
}
{#code_end#}
{#header_close#}
2019-11-20 22:11:07 +00:00
2019-11-24 03:29:12 +00:00
{#header_open|Sentinel-Terminated Pointers#}
2019-11-20 22:11:07 +00:00
< p >
2019-11-24 03:29:12 +00:00
The syntax {#syntax#}[*:x]T{#endsyntax#} describes a pointer that
has a length determined by a sentinel value. This provides protection
2019-11-20 22:11:07 +00:00
against buffer overflow and overreads.
< / p >
{#code_begin|exe_build_err#}
2020-01-14 02:19:50 +00:00
{#link_libc#}
2019-11-20 22:11:07 +00:00
const std = @import("std");
// This is also available as `std.c.printf`.
2019-11-24 03:29:12 +00:00
pub extern "c" fn printf(format: [*:0]const u8, ...) c_int;
2019-11-20 22:11:07 +00:00
pub fn main() anyerror!void {
_ = printf("Hello, world!\n"); // OK
const msg = "Hello, world!\n";
const non_null_terminated_msg: [msg.len]u8 = msg.*;
_ = printf(&non_null_terminated_msg);
}
{#code_end#}
2019-11-24 03:29:12 +00:00
{#see_also|Sentinel-Terminated Slices|Sentinel-Terminated Arrays#}
2019-11-20 22:11:07 +00:00
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2019-02-14 23:59:20 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|Slices#}
2018-01-19 08:03:20 +00:00
{#code_begin|test_safety|index out of bounds#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
test "basic slices" {
2019-06-10 00:24:24 +01:00
var array = [_]i32{ 1, 2, 3, 4 };
2017-11-07 08:22:27 +00:00
// A slice is a pointer and a length. The difference between an array and
// a slice is that the array's length is part of the type and known at
// compile-time, whereas the slice's length is known at runtime.
// Both can be accessed with the `len` field.
2020-03-19 01:25:35 +00:00
var known_at_runtime_zero: usize = 0;
const slice = array[known_at_runtime_zero..array.len];
2018-06-04 06:09:15 +01:00
assert(& slice[0] == &array[0]);
2017-11-07 08:22:27 +00:00
assert(slice.len == array.len);
2018-06-04 06:09:15 +01:00
// Using the address-of operator on a slice gives a pointer to a single
// item, while using the `ptr` field gives an unknown length pointer.
2019-12-09 20:59:42 +00:00
assert(@TypeOf(slice.ptr) == [*]i32);
assert(@TypeOf(& slice[0]) == *i32);
2018-06-04 06:09:15 +01:00
assert(@ptrToInt(slice.ptr) == @ptrToInt(&slice[0]));
2017-11-07 08:22:27 +00:00
// Slices have array bounds checking. If you try to access something out
// of bounds, you'll get a safety check failure:
slice[10] += 1;
2018-06-04 06:09:15 +01:00
// Note that `slice.ptr` does not invoke safety checking, while `& slice[0]`
// asserts that the slice has len >= 1.
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p > This is one reason we prefer slices to pointers.< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test|slices#}
2020-03-19 01:25:35 +00:00
const std = @import("std");
const assert = std.debug.assert;
const mem = std.mem;
const fmt = std.fmt;
2017-11-07 08:22:27 +00:00
test "using slices for strings" {
2020-03-19 01:25:35 +00:00
// Zig has no concept of strings. String literals are const pointers to
// arrays of u8, and by convention parameters that are "strings" are
// expected to be UTF-8 encoded slices of u8.
2019-11-08 20:56:21 +00:00
// Here we coerce [5]u8 to []const u8
2017-11-07 08:22:27 +00:00
const hello: []const u8 = "hello";
const world: []const u8 = "世界";
var all_together: [100]u8 = undefined;
// You can use slice syntax on an array to convert an array into a slice.
const all_together_slice = all_together[0..];
2018-01-19 08:03:20 +00:00
// String concatenation example.
2020-03-19 01:25:35 +00:00
const hello_world = try fmt.bufPrint(all_together_slice, "{} {}", .{ hello, world });
2017-11-07 08:22:27 +00:00
// Generally, you can use UTF-8 and not worry about whether something is a
// string. If you don't need to deal with individual characters, no need
// to decode.
assert(mem.eql(u8, hello_world, "hello 世界"));
}
test "slice pointer" {
var array: [10]u8 = undefined;
2018-06-05 03:11:14 +01:00
const ptr = &array;
2017-11-07 08:22:27 +00:00
// You can use slicing syntax to convert a pointer into a slice:
const slice = ptr[0..5];
slice[2] = 3;
assert(slice[2] == 3);
// The slice is mutable because we sliced a mutable pointer.
2020-03-19 01:25:35 +00:00
// Furthermore, it is actually a pointer to an array, since the start
// and end indexes were both comptime-known.
assert(@TypeOf(slice) == *[5]u8);
2017-11-07 08:22:27 +00:00
// You can also slice a slice:
const slice2 = slice[2..3];
assert(slice2.len == 1);
assert(slice2[0] == 3);
}
2018-01-19 08:03:20 +00:00
{#code_end#}
2018-01-17 05:22:33 +00:00
{#see_also|Pointers|for|Arrays#}
2019-11-20 22:11:07 +00:00
2019-11-24 03:29:12 +00:00
{#header_open|Sentinel-Terminated Slices#}
2019-11-20 22:11:07 +00:00
< p >
2019-11-24 03:29:12 +00:00
The syntax {#syntax#}[:x]T{#endsyntax#} is a slice which has a runtime known length
and also guarantees a sentinel value at the element indexed by the length. The type does not
guarantee that there are no sentinel elements before that. Sentinel-terminated slices allow element
2019-11-20 22:11:07 +00:00
access to the {#syntax#}len{#endsyntax#} index.
< / p >
{#code_begin|test|null_terminated_slice#}
const std = @import("std");
const assert = std.debug.assert;
test "null terminated slice" {
2019-11-24 03:29:12 +00:00
const slice: [:0]const u8 = "hello";
2019-11-20 22:11:07 +00:00
assert(slice.len == 5);
assert(slice[5] == 0);
}
{#code_end#}
2019-11-24 03:29:12 +00:00
{#see_also|Sentinel-Terminated Pointers|Sentinel-Terminated Arrays#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2019-11-20 22:11:07 +00:00
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|struct#}
2018-01-19 08:03:20 +00:00
{#code_begin|test|structs#}
// Declare a struct.
2019-07-11 22:40:54 +01:00
// Zig gives no guarantees about the order of fields and the size of
// the struct but the fields are guaranteed to be ABI-aligned.
2018-11-13 13:08:37 +00:00
const Point = struct {
2017-11-07 08:22:27 +00:00
x: f32,
y: f32,
};
// Maybe we want to pass it to OpenGL so we want to be particular about
// how the bytes are arranged.
2018-11-13 13:08:37 +00:00
const Point2 = packed struct {
2017-11-07 08:22:27 +00:00
x: f32,
y: f32,
};
// Declare an instance of a struct.
2018-11-13 13:08:37 +00:00
const p = Point {
2017-11-07 08:22:27 +00:00
.x = 0.12,
.y = 0.34,
};
// Maybe we're not ready to fill out some of the fields.
2018-11-13 13:08:37 +00:00
var p2 = Point {
2017-11-07 08:22:27 +00:00
.x = 0.12,
.y = undefined,
};
// Structs can have methods
// Struct methods are not special, they are only namespaced
// functions that you can call with dot syntax.
2018-11-13 13:08:37 +00:00
const Vec3 = struct {
2017-11-07 08:22:27 +00:00
x: f32,
y: f32,
z: f32,
2018-01-25 09:10:11 +00:00
pub fn init(x: f32, y: f32, z: f32) Vec3 {
2018-11-13 13:08:37 +00:00
return Vec3 {
2017-11-07 08:22:27 +00:00
.x = x,
.y = y,
.z = z,
};
}
2018-10-15 23:23:47 +01:00
pub fn dot(self: Vec3, other: Vec3) f32 {
2017-11-07 08:22:27 +00:00
return self.x * other.x + self.y * other.y + self.z * other.z;
}
};
const assert = @import("std").debug.assert;
test "dot product" {
const v1 = Vec3.init(1.0, 0.0, 0.0);
const v2 = Vec3.init(0.0, 1.0, 0.0);
assert(v1.dot(v2) == 0.0);
// Other than being available to call with dot syntax, struct methods are
// not special. You can reference them as any other declaration inside
// the struct:
assert(Vec3.dot(v1, v2) == 0.0);
}
// Structs can have global declarations.
// Structs can have 0 fields.
2018-11-13 13:08:37 +00:00
const Empty = struct {
2017-11-07 08:22:27 +00:00
pub const PI = 3.14;
};
test "struct namespaced variable" {
assert(Empty.PI == 3.14);
assert(@sizeOf(Empty) == 0);
// you can still instantiate an empty struct
2018-11-13 13:08:37 +00:00
const does_nothing = Empty {};
2017-11-07 08:22:27 +00:00
}
// struct field order is determined by the compiler for optimal performance.
// however, you can still calculate a struct base pointer given a field pointer:
2018-05-31 15:56:59 +01:00
fn setYBasedOnX(x: *f32, y: f32) void {
2017-11-07 08:22:27 +00:00
const point = @fieldParentPtr(Point, "x", x);
point.y = y;
}
test "field parent pointer" {
2018-11-13 13:08:37 +00:00
var point = Point {
2017-11-07 08:22:27 +00:00
.x = 0.1234,
.y = 0.5678,
};
2018-01-19 08:03:20 +00:00
setYBasedOnX(& point.x, 0.9);
2017-11-07 08:22:27 +00:00
assert(point.y == 0.9);
}
// You can return a struct from a function. This is how we do generics
// in Zig:
2018-01-25 09:10:11 +00:00
fn LinkedList(comptime T: type) type {
2018-11-13 13:08:37 +00:00
return struct {
pub const Node = struct {
2018-05-31 15:56:59 +01:00
prev: ?*Node,
next: ?*Node,
2017-11-07 08:22:27 +00:00
data: T,
};
2018-05-31 15:56:59 +01:00
first: ?*Node,
last: ?*Node,
2017-11-07 08:22:27 +00:00
len: usize,
};
}
test "linked list" {
// Functions called at compile-time are memoized. This means you can
// do this:
assert(LinkedList(i32) == LinkedList(i32));
2018-11-13 13:08:37 +00:00
var list = LinkedList(i32) {
2017-11-07 08:22:27 +00:00
.first = null,
.last = null,
.len = 0,
};
assert(list.len == 0);
// Since types are first class values you can instantiate the type
// by assigning it to a variable:
const ListOfInts = LinkedList(i32);
assert(ListOfInts == LinkedList(i32));
2018-11-13 13:08:37 +00:00
var node = ListOfInts.Node {
2017-11-07 08:22:27 +00:00
.prev = null,
.next = null,
.data = 1234,
};
2018-11-13 13:08:37 +00:00
var list2 = LinkedList(i32) {
2018-01-19 08:03:20 +00:00
.first = & node,
.last = & node,
2017-11-07 08:22:27 +00:00
.len = 1,
};
2018-06-10 04:42:14 +01:00
assert(list2.first.?.data == 1234);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2019-02-27 03:46:35 +00:00
2019-05-30 20:35:30 +01:00
{#header_open|Default Field Values#}
< p >
Each struct field may have an expression indicating the default field value. Such expressions
are executed at {#link|comptime#}, and allow the field to be omitted in a struct literal expression:
< / p >
{#code_begin|test#}
const Foo = struct {
a: i32 = 1234,
b: i32,
};
test "default struct initialization fields" {
const x = Foo{
.b = 5,
};
if (x.a + x.b != 1239) {
@compileError("it's even comptime known!");
}
}
{#code_end#}
{#header_close#}
2019-02-27 03:46:35 +00:00
{#header_open|extern struct#}
< p > An {#syntax#}extern struct{#endsyntax#} has in-memory layout guaranteed to match the
C ABI for the target.< / p >
2019-04-04 06:23:41 +01:00
< p > This kind of struct should only be used for compatibility with the C ABI. Every other
use case should be solved with {#link|packed struct#} or normal {#link|struct#}.< / p >
2019-02-27 03:46:35 +00:00
{#see_also|extern union|extern enum#}
{#header_close#}
2018-09-21 19:15:58 +01:00
{#header_open|packed struct#}
2019-02-22 15:56:49 +00:00
< p >
Unlike normal structs, {#syntax#}packed{#endsyntax#} structs have guaranteed in-memory layout:
< / p >
< ul >
< li > Fields remain in the order declared.< / li >
< li > There is no padding between fields.< / li >
< li > Zig supports arbitrary width {#link|Integers#} and although normally, integers with fewer
than 8 bits will still use 1 byte of memory, in packed structs, they use
exactly their bit width.
< / li >
< li > {#syntax#}bool{#endsyntax#} fields use exactly 1 bit.< / li >
< li > A {#link|packed enum#} field uses exactly the bit width of its integer tag type.< / li >
< li > A {#link|packed union#} field uses exactly the bit width of the union field with
the largest bit width.< / li >
2019-04-02 19:44:25 +01:00
< li > Non-ABI-aligned fields are packed into the smallest possible
ABI-aligned integers in accordance with the target endianness.
2019-02-22 15:56:49 +00:00
< / li >
< / ul >
< p >
This means that a {#syntax#}packed struct{#endsyntax#} can participate
in a {#link|@bitCast#} or a {#link|@ptrCast#} to reinterpret memory.
This even works at {#link|comptime#}:
< / p >
{#code_begin|test#}
const std = @import("std");
2020-02-27 19:41:44 +00:00
const builtin = std.builtin;
2019-02-22 15:56:49 +00:00
const assert = std.debug.assert;
const Full = packed struct {
number: u16,
};
const Divided = packed struct {
half1: u8,
quarter3: u4,
quarter4: u4,
};
test "@bitCast between packed structs" {
doTheTest();
comptime doTheTest();
}
fn doTheTest() void {
assert(@sizeOf(Full) == 2);
assert(@sizeOf(Divided) == 2);
var full = Full{ .number = 0x1234 };
var divided = @bitCast(Divided, full);
switch (builtin.endian) {
2019-07-04 04:09:58 +01:00
.Big => {
2019-02-22 15:56:49 +00:00
assert(divided.half1 == 0x12);
assert(divided.quarter3 == 0x3);
assert(divided.quarter4 == 0x4);
},
2019-07-04 04:09:58 +01:00
.Little => {
2019-02-22 15:56:49 +00:00
assert(divided.half1 == 0x34);
assert(divided.quarter3 == 0x2);
assert(divided.quarter4 == 0x1);
},
}
}
{#code_end#}
< p >
Zig allows the address to be taken of a non-byte-aligned field:
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
const BitField = packed struct {
a: u3,
b: u3,
c: u2,
};
var foo = BitField{
.a = 1,
.b = 2,
.c = 3,
};
test "pointer to non-byte-aligned field" {
const ptr = &foo.b;
assert(ptr.* == 2);
}
{#code_end#}
< p >
However, the pointer to a non-byte-aligned field has special properties and cannot
be passed when a normal pointer is expected:
< / p >
{#code_begin|test_err|expected type#}
const std = @import("std");
const assert = std.debug.assert;
const BitField = packed struct {
a: u3,
b: u3,
c: u2,
};
var bit_field = BitField{
.a = 1,
.b = 2,
.c = 3,
};
test "pointer to non-bit-aligned field" {
assert(bar(& bit_field.b) == 2);
}
fn bar(x: *const u3) u3 {
return x.*;
}
{#code_end#}
< p >
In this case, the function {#syntax#}bar{#endsyntax#} cannot be called becuse the pointer
2019-04-02 19:44:25 +01:00
to the non-ABI-aligned field mentions the bit offset, but the function expects an ABI-aligned pointer.
2019-02-22 15:56:49 +00:00
< / p >
< p >
2019-04-02 19:44:25 +01:00
Pointers to non-ABI-aligned fields share the same address as the other fields within their host integer:
2019-02-22 15:56:49 +00:00
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
const BitField = packed struct {
a: u3,
b: u3,
c: u2,
};
var bit_field = BitField{
.a = 1,
.b = 2,
.c = 3,
};
test "pointer to non-bit-aligned field" {
assert(@ptrToInt(& bit_field.a) == @ptrToInt(&bit_field.b));
assert(@ptrToInt(& bit_field.a) == @ptrToInt(&bit_field.c));
}
{#code_end#}
< p >
This can be observed with {#link|@bitOffsetOf#} and {#link|byteOffsetOf#}:
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
const BitField = packed struct {
a: u3,
b: u3,
c: u2,
};
test "pointer to non-bit-aligned field" {
comptime {
assert(@bitOffsetOf(BitField, "a") == 0);
assert(@bitOffsetOf(BitField, "b") == 3);
assert(@bitOffsetOf(BitField, "c") == 6);
assert(@byteOffsetOf(BitField, "a") == 0);
assert(@byteOffsetOf(BitField, "b") == 0);
assert(@byteOffsetOf(BitField, "c") == 0);
}
}
{#code_end#}
< p >
Packed structs have 1-byte alignment. However if you have an overaligned pointer to a packed struct,
Zig should correctly understand the alignment of fields. However there is
< a href = "https://github.com/ziglang/zig/issues/1994" > a bug< / a > :
< / p >
{#code_begin|test_err#}
const S = packed struct {
a: u32,
b: u32,
};
test "overaligned pointer to packed struct" {
var foo: S align(4) = undefined;
const ptr: *align(4) S = &foo;
const ptr_to_b: *u32 = &ptr.b;
}
{#code_end#}
< p > When this bug is fixed, the above test in the documentation will unexpectedly pass, which will
cause the test suite to fail, notifying the bug fixer to update these docs.
< / p >
< p >
It's also
< a href = "https://github.com/ziglang/zig/issues/1512" > planned to be able to set alignment of struct fields< / a > .
< / p >
< p >
Using packed structs with {#link|volatile#} is problematic, and may be a compile error in the future.
For details on this subscribe to
< a href = "https://github.com/ziglang/zig/issues/1761" > this issue< / a > .
TODO update these docs with a recommendation on how to use packed structs with MMIO
(the use case for volatile packed structs) once this issue is resolved.
Don't worry, there will be a good solution for this use case in zig.
< / p >
2018-09-21 19:15:58 +01:00
{#header_close#}
2019-11-12 00:57:57 +00:00
{#header_open|Struct Naming#}
2018-09-03 16:32:39 +01:00
< p > Since all structs are anonymous, Zig infers the type name based on a few rules.< / p >
< ul >
< li > If the struct is in the initialization expression of a variable, it gets named after
that variable.< / li >
2018-09-14 15:35:03 +01:00
< li > If the struct is in the {#syntax#}return{#endsyntax#} expression, it gets named after
2018-09-03 16:32:39 +01:00
the function it is returning from, with the parameter values serialized.< / li >
2018-09-25 17:03:09 +01:00
< li > Otherwise, the struct gets a name such as < code > (anonymous struct at file.zig:7:38)< / code > .< / li >
2018-09-03 16:32:39 +01:00
< / ul >
{#code_begin|exe|struct_name#}
const std = @import("std");
pub fn main() void {
2018-11-13 13:08:37 +00:00
const Foo = struct {};
2020-06-19 10:38:22 +01:00
std.debug.print("variable: {}\n", .{@typeName(Foo)});
std.debug.print("anonymous: {}\n", .{@typeName(struct {})});
std.debug.print("function: {}\n", .{@typeName(List(i32))});
2018-09-03 16:32:39 +01:00
}
fn List(comptime T: type) type {
2018-11-13 13:08:37 +00:00
return struct {
2018-09-03 16:32:39 +01:00
x: T,
};
}
{#code_end#}
{#header_close#}
2019-11-12 00:57:57 +00:00
{#header_open|Anonymous Struct Literals#}
< p >
Zig allows omitting the struct type of a literal. When the result is {#link|coerced|Type Coercion#},
the struct literal will directly instantiate the result location, with no copy:
< / p >
{#code_begin|test|struct_result#}
const std = @import("std");
const assert = std.debug.assert;
const Point = struct {x: i32, y: i32};
test "anonymous struct literal" {
var pt: Point = .{
.x = 13,
.y = 67,
};
assert(pt.x == 13);
assert(pt.y == 67);
}
{#code_end#}
< p >
The struct type can be inferred. Here the result location does not include a type, and
so Zig infers the type:
< / p >
{#code_begin|test|struct_anon#}
const std = @import("std");
const assert = std.debug.assert;
test "fully anonymous struct" {
dump(.{
.int = @as(u32, 1234),
.float = @as(f64, 12.34),
.b = true,
.s = "hi",
});
}
2020-07-11 12:08:20 +01:00
fn dump(args: anytype) void {
2019-11-12 00:57:57 +00:00
assert(args.int == 1234);
assert(args.float == 12.34);
assert(args.b);
assert(args.s[0] == 'h');
assert(args.s[1] == 'i');
}
{#code_end#}
{#header_close#}
2018-01-17 05:22:33 +00:00
{#see_also|comptime|@fieldParentPtr#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|enum#}
2018-01-19 08:03:20 +00:00
{#code_begin|test|enums#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
const mem = @import("std").mem;
// Declare an enum.
2018-11-13 13:08:37 +00:00
const Type = enum {
2020-10-14 16:34:05 +01:00
ok,
not_ok,
2017-11-07 08:22:27 +00:00
};
// Declare a specific instance of the enum variant.
2020-10-14 16:34:05 +01:00
const c = Type.ok;
2017-11-07 08:22:27 +00:00
2017-12-04 06:42:02 +00:00
// If you want access to the ordinal value of an enum, you
// can specify the tag type.
2018-11-13 13:08:37 +00:00
const Value = enum(u2) {
2020-10-14 16:34:05 +01:00
zero,
one,
two,
2017-11-07 08:22:27 +00:00
};
2017-12-04 06:42:02 +00:00
// Now you can cast between u2 and Value.
// The ordinal value starts from 0, counting up for each member.
2017-11-07 08:22:27 +00:00
test "enum ordinal value" {
2020-10-14 16:34:05 +01:00
assert(@enumToInt(Value.zero) == 0);
assert(@enumToInt(Value.one) == 1);
assert(@enumToInt(Value.two) == 2);
2017-12-04 06:42:02 +00:00
}
// You can override the ordinal value for an enum.
2018-11-13 13:08:37 +00:00
const Value2 = enum(u32) {
2020-10-14 16:34:05 +01:00
hundred = 100,
thousand = 1000,
million = 1000000,
2017-12-04 06:42:02 +00:00
};
test "set enum ordinal value" {
2020-10-14 16:34:05 +01:00
assert(@enumToInt(Value2.hundred) == 100);
assert(@enumToInt(Value2.thousand) == 1000);
assert(@enumToInt(Value2.million) == 1000000);
2017-11-07 08:22:27 +00:00
}
2017-12-04 06:42:02 +00:00
// Enums can have methods, the same as structs and unions.
2017-11-07 08:22:27 +00:00
// Enum methods are not special, they are only namespaced
// functions that you can call with dot syntax.
2018-11-13 13:08:37 +00:00
const Suit = enum {
2020-10-14 16:34:05 +01:00
clubs,
spades,
diamonds,
hearts,
2017-11-07 08:22:27 +00:00
2018-01-25 09:10:11 +00:00
pub fn isClubs(self: Suit) bool {
2020-10-14 16:34:05 +01:00
return self == Suit.clubs;
2017-11-07 08:22:27 +00:00
}
};
test "enum method" {
2020-10-14 16:34:05 +01:00
const p = Suit.spades;
2017-12-04 06:42:02 +00:00
assert(!p.isClubs());
2017-11-07 08:22:27 +00:00
}
// An enum variant of different types can be switched upon.
2018-11-13 13:08:37 +00:00
const Foo = enum {
2020-10-14 16:34:05 +01:00
string,
number,
none,
2017-12-04 06:42:02 +00:00
};
test "enum variant switch" {
2020-10-14 16:34:05 +01:00
const p = Foo.number;
2017-12-04 06:42:02 +00:00
const what_is_it = switch (p) {
2020-10-14 16:34:05 +01:00
Foo.string => "this is a string",
Foo.number => "this is a number",
Foo.none => "this is a none",
2017-12-04 06:42:02 +00:00
};
assert(mem.eql(u8, what_is_it, "this is a number"));
}
// @TagType can be used to access the integer tag type of an enum.
2018-11-13 13:08:37 +00:00
const Small = enum {
2020-10-14 16:34:05 +01:00
one,
two,
three,
four,
2017-12-04 06:42:02 +00:00
};
test "@TagType" {
assert(@TagType(Small) == u2);
}
2020-02-24 21:50:02 +00:00
// @typeInfo tells us the field count and the fields names:
2020-02-24 21:21:11 +00:00
test "@typeInfo" {
assert(@typeInfo(Small).Enum.fields.len == 4);
2020-10-14 16:34:05 +01:00
assert(mem.eql(u8, @typeInfo(Small).Enum.fields[1].name, "two"));
2017-12-04 06:42:02 +00:00
}
// @tagName gives a []const u8 representation of an enum value:
test "@tagName" {
2020-10-14 16:34:05 +01:00
assert(mem.eql(u8, @tagName(Small.three), "three"));
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2020-02-24 21:21:11 +00:00
{#see_also|@typeInfo|@tagName|@sizeOf#}
2019-07-04 04:09:58 +01:00
2018-01-23 03:24:07 +00:00
{#header_open|extern enum#}
< p >
By default, enums are not guaranteed to be compatible with the C ABI:
< / p >
2019-12-23 20:52:06 +00:00
{#code_begin|obj_err|parameter of type 'Foo' not allowed in function with calling convention 'C'#}
2020-10-14 16:34:05 +01:00
const Foo = enum { a, b, c };
2018-01-25 09:10:11 +00:00
export fn entry(foo: Foo) void { }
2018-01-23 03:24:07 +00:00
{#code_end#}
< p >
2018-09-14 15:35:03 +01:00
For a C-ABI-compatible enum, use {#syntax#}extern enum{#endsyntax#}:
2018-01-23 03:24:07 +00:00
< / p >
{#code_begin|obj#}
2020-10-14 16:34:05 +01:00
const Foo = extern enum { a, b, c };
2018-01-25 09:10:11 +00:00
export fn entry(foo: Foo) void { }
2018-01-23 03:24:07 +00:00
{#code_end#}
{#header_close#}
2019-07-04 04:09:58 +01:00
2018-04-07 00:14:49 +01:00
{#header_open|packed enum#}
< p > By default, the size of enums is not guaranteed.< / p >
2019-02-22 15:56:49 +00:00
< p > {#syntax#}packed enum{#endsyntax#} causes the size of the enum to be the same as the size of the
integer tag type of the enum:< / p >
2018-04-07 00:14:49 +01:00
{#code_begin|test#}
const std = @import("std");
test "packed enum" {
2018-11-13 13:08:37 +00:00
const Number = packed enum(u8) {
2020-10-14 16:34:05 +01:00
one,
two,
three,
2018-04-07 00:14:49 +01:00
};
std.debug.assert(@sizeOf(Number) == @sizeOf(u8));
}
{#code_end#}
2019-02-22 15:56:49 +00:00
< p > This makes the enum eligible to be in a {#link|packed struct#}.< / p >
2018-04-07 00:14:49 +01:00
{#header_close#}
2019-07-04 04:09:58 +01:00
{#header_open|Enum Literals#}
< p >
Enum literals allow specifying the name of an enum field without specifying the enum type:
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
const Color = enum {
2020-10-14 16:34:05 +01:00
auto,
off,
on,
2019-07-04 04:09:58 +01:00
};
test "enum literals" {
2020-10-14 16:34:05 +01:00
const color1: Color = .auto;
const color2 = Color.auto;
2019-07-04 04:09:58 +01:00
assert(color1 == color2);
}
test "switch using enum literals" {
2020-10-14 16:34:05 +01:00
const color = Color.on;
2019-07-04 04:09:58 +01:00
const result = switch (color) {
2020-10-14 16:34:05 +01:00
.auto => false,
.on => true,
.off => false,
2019-07-04 04:09:58 +01:00
};
assert(result);
}
{#code_end#}
{#header_close#}
2020-01-15 21:05:52 +00:00
{#header_open|Non-exhaustive enum#}
< p >
A Non-exhaustive enum can be created by adding a trailing '_' field.
It must specify a tag type and cannot consume every enumeration value.
< / p >
< p >
{#link|@intToEnum#} on a non-exhaustive enum cannot fail.
< / p >
< p >
2020-01-16 07:04:11 +00:00
A switch on a non-exhaustive enum can include a '_' prong as an alternative to an {#syntax#}else{#endsyntax#} prong
with the difference being that it makes it a compile error if all the known tag names are not handled by the switch.
2020-01-15 21:05:52 +00:00
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
const Number = enum(u8) {
2020-10-14 16:34:05 +01:00
one,
two,
three,
2020-01-15 21:05:52 +00:00
_,
};
test "switch on non-exhaustive enum" {
2020-10-14 16:34:05 +01:00
const number = Number.one;
2020-01-15 21:05:52 +00:00
const result = switch (number) {
2020-10-14 16:34:05 +01:00
.one => true,
.two,
.three => false,
2020-01-15 21:05:52 +00:00
_ => false,
};
assert(result);
const is_one = switch (number) {
2020-10-14 16:34:05 +01:00
.one => true,
2020-01-15 21:05:52 +00:00
else => false,
};
assert(is_one);
}
{#code_end#}
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2019-07-04 04:09:58 +01:00
2018-01-17 04:19:05 +00:00
{#header_open|union#}
2019-02-27 03:46:35 +00:00
< p >
A bare {#syntax#}union{#endsyntax#} defines a set of possible types that a value
can be as a list of fields. Only one field can be active at a time.
The in-memory representation of bare unions is not guaranteed.
Bare unions cannot be used to reinterpret memory. For that, use {#link|@ptrCast#},
or use an {#link|extern union#} or a {#link|packed union#} which have
guaranteed in-memory layout.
{#link|Accessing the non-active field|Wrong Union Field Access#} is
safety-checked {#link|Undefined Behavior#}:
< / p >
{#code_begin|test_err|inactive union field#}
const Payload = union {
2020-10-14 16:34:05 +01:00
int: i64,
float: f64,
boolean: bool,
2019-02-27 03:46:35 +00:00
};
test "simple union" {
2020-10-14 16:34:05 +01:00
var payload = Payload{ .int = 1234 };
payload.float = 12.34;
2019-02-27 03:46:35 +00:00
}
{#code_end#}
< p > You can activate another field by assigning the entire union:< / p >
{#code_begin|test#}
2019-02-18 17:56:17 +00:00
const std = @import("std");
const assert = std.debug.assert;
2017-12-04 06:42:02 +00:00
2018-11-13 13:08:37 +00:00
const Payload = union {
2020-10-14 16:34:05 +01:00
int: i64,
float: f64,
boolean: bool,
2017-12-04 06:42:02 +00:00
};
test "simple union" {
2020-10-14 16:34:05 +01:00
var payload = Payload{ .int = 1234 };
assert(payload.int == 1234);
payload = Payload{ .float = 12.34 };
assert(payload.float == 12.34);
2017-12-04 06:42:02 +00:00
}
2019-02-27 03:46:35 +00:00
{#code_end#}
< p >
In order to use {#link|switch#} with a union, it must be a {#link|Tagged union#}.
< / p >
2019-07-05 19:10:50 +01:00
< p >
To initialize a union when the tag is a {#link|comptime#}-known name, see {#link|@unionInit#}.
< / p >
2019-02-27 03:46:35 +00:00
{#header_open|Tagged union#}
< p > Unions can be declared with an enum tag type.
This turns the union into a < em > tagged< / em > union, which makes it eligible
to use with {#link|switch#} expressions. One can use {#link|@TagType#} to
obtain the enum type from the union type.
2020-03-23 23:00:52 +00:00
Tagged unions coerce to their tag type: {#link|Type Coercion: unions and enums#}.
2019-02-27 03:46:35 +00:00
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
2017-12-04 06:42:02 +00:00
2019-02-18 17:56:17 +00:00
const ComplexTypeTag = enum {
2020-10-14 16:34:05 +01:00
ok,
not_ok,
2019-02-18 17:56:17 +00:00
};
2018-11-13 13:08:37 +00:00
const ComplexType = union(ComplexTypeTag) {
2020-10-14 16:34:05 +01:00
ok: u8,
not_ok: void,
2017-12-04 06:42:02 +00:00
};
2019-02-27 03:46:35 +00:00
test "switch on tagged union" {
2020-10-14 16:34:05 +01:00
const c = ComplexType{ .ok = 42 };
assert(@as(ComplexTypeTag, c) == ComplexTypeTag.ok);
2019-02-27 03:46:35 +00:00
switch (c) {
2020-10-14 16:34:05 +01:00
ComplexTypeTag.ok => |value| assert(value == 42),
ComplexTypeTag.not_ok => unreachable,
2019-02-27 03:46:35 +00:00
}
2017-12-04 06:42:02 +00:00
}
test "@TagType" {
assert(@TagType(ComplexType) == ComplexTypeTag);
}
2019-10-27 20:35:22 +00:00
2019-11-08 20:56:21 +00:00
test "coerce to enum" {
2020-10-14 16:34:05 +01:00
const c1 = ComplexType{ .ok = 42 };
const c2 = ComplexType.not_ok;
2019-10-27 20:35:22 +00:00
2020-10-14 16:34:05 +01:00
assert(c1 == .ok);
assert(c2 == .not_ok);
2019-10-27 20:35:22 +00:00
}
2019-02-27 03:46:35 +00:00
{#code_end#}
< p > In order to modify the payload of a tagged union in a switch expression,
place a {#syntax#}*{#endsyntax#} before the variable name to make it a pointer:
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
2017-12-04 06:42:02 +00:00
2019-02-27 03:46:35 +00:00
const ComplexTypeTag = enum {
2020-10-14 16:34:05 +01:00
ok,
not_ok,
2019-02-27 03:46:35 +00:00
};
const ComplexType = union(ComplexTypeTag) {
2020-10-14 16:34:05 +01:00
ok: u8,
not_ok: void,
2017-11-07 08:22:27 +00:00
};
2019-02-27 03:46:35 +00:00
test "modify tagged union in switch" {
2020-10-14 16:34:05 +01:00
var c = ComplexType{ .ok = 42 };
assert(@as(ComplexTypeTag, c) == ComplexTypeTag.ok);
2017-11-07 08:22:27 +00:00
2019-02-27 03:46:35 +00:00
switch (c) {
2020-10-14 16:34:05 +01:00
ComplexTypeTag.ok => |*value| value.* += 1,
ComplexTypeTag.not_ok => unreachable,
2019-02-27 03:46:35 +00:00
}
2017-11-07 08:22:27 +00:00
2020-10-14 16:34:05 +01:00
assert(c.ok == 43);
2019-02-27 03:46:35 +00:00
}
{#code_end#}
< p >
Unions can be made to infer the enum tag type.
Further, unions can have methods just like structs and enums.
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
2018-04-08 23:03:02 +01:00
2018-11-13 13:08:37 +00:00
const Variant = union(enum) {
2020-10-14 16:34:05 +01:00
int: i32,
boolean: bool,
2018-04-08 23:03:02 +01:00
2019-02-27 03:46:35 +00:00
// void can be omitted when inferring enum tag type.
2020-10-14 16:34:05 +01:00
none,
2019-02-27 03:46:35 +00:00
2018-10-15 23:23:47 +01:00
fn truthy(self: Variant) bool {
return switch (self) {
2020-10-14 16:34:05 +01:00
Variant.int => |x_int| x_int != 0,
Variant.boolean => |x_bool| x_bool,
Variant.none => false,
2018-04-08 23:03:02 +01:00
};
}
};
test "union method" {
2020-10-14 16:34:05 +01:00
var v1 = Variant{ .int = 1 };
var v2 = Variant{ .boolean = false };
2018-04-08 23:03:02 +01:00
assert(v1.truthy());
assert(!v2.truthy());
}
2019-02-27 03:46:35 +00:00
{#code_end#}
< p >
{#link|@tagName#} can be used to return a {#link|comptime#}
{#syntax#}[]const u8{#endsyntax#} value representing the field name:
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
2017-12-04 06:42:02 +00:00
2018-11-13 13:08:37 +00:00
const Small2 = union(enum) {
2020-10-14 16:34:05 +01:00
a: i32,
b: bool,
c: u8,
2017-12-04 06:42:02 +00:00
};
test "@tagName" {
2020-10-14 16:34:05 +01:00
assert(std.mem.eql(u8, @tagName(Small2.a), "a"));
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2019-02-27 03:46:35 +00:00
{#header_close#}
{#header_open|extern union#}
2017-11-07 08:22:27 +00:00
< p >
2019-02-27 03:46:35 +00:00
An {#syntax#}extern union{#endsyntax#} has memory layout guaranteed to be compatible with
the target C ABI.
2017-11-07 08:22:27 +00:00
< / p >
2019-02-27 03:46:35 +00:00
{#see_also|extern struct#}
{#header_close#}
2019-02-22 15:56:49 +00:00
{#header_open|packed union#}
< p > A {#syntax#}packed union{#endsyntax#} has well-defined in-memory layout and is eligible
to be in a {#link|packed struct#}.
{#header_close#}
2019-11-12 00:57:57 +00:00
{#header_open|Anonymous Union Literals#}
< p > {#link|Anonymous Struct Literals#} syntax can be used to initialize unions without specifying
the type:< / p >
{#code_begin|test|anon_union#}
const std = @import("std");
const assert = std.debug.assert;
const Number = union {
int: i32,
float: f64,
};
test "anonymous union literal syntax" {
var i: Number = .{.int = 42};
var f = makeNumber();
assert(i.int == 42);
assert(f.float == 12.34);
}
fn makeNumber() Number {
return .{.float = 12.34};
}
{#code_end#}
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2019-02-22 15:56:49 +00:00
2020-10-17 05:29:33 +01:00
{#header_open|opaque#}
< p >
{#syntax#}opaque {}{#endsyntax#} declares a new type with an unknown (but non-zero) size and alignment.
It can contain declarations the same as {#link|structs|struct#}, {#link|unions|union#},
and {#link|enums|enum#}.
< / p >
< p >
This is typically used for type safety when interacting with C code that does not expose struct details.
Example:
< / p >
{#code_begin|test_err|expected type '*Derp', found '*Wat'#}
const Derp = opaque {};
const Wat = opaque {};
extern fn bar(d: *Derp) void;
fn foo(w: *Wat) callconv(.C) void {
bar(w);
}
test "call foo" {
foo(undefined);
}
{#code_end#}
{#header_close#}
2018-08-28 01:59:28 +01:00
{#header_open|blocks#}
< p >
Blocks are used to limit the scope of variable declarations:
< / p >
{#code_begin|test_err|undeclared identifier#}
test "access variable after block scope" {
{
var x: i32 = 1;
}
x += 1;
}
{#code_end#}
2018-09-14 15:35:03 +01:00
< p > Blocks are expressions. When labeled, {#syntax#}break{#endsyntax#} can be used
2018-08-28 01:59:28 +01:00
to return a value from the block:
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
test "labeled break from labeled block expression" {
var y: i32 = 123;
const x = blk: {
y += 1;
break :blk y;
};
assert(x == 124);
assert(y == 124);
}
{#code_end#}
2018-09-14 15:35:03 +01:00
< p > Here, {#syntax#}blk{#endsyntax#} can be any name.< / p >
2018-08-28 01:59:28 +01:00
{#see_also|Labeled while|Labeled for#}
2019-02-18 22:49:26 +00:00
{#header_open|Shadowing#}
< p > It is never allowed for an identifier to "hide" another one by using the same name:< / p >
{#code_begin|test_err|redefinition#}
const pi = 3.14;
test "inside test block" {
// Let's even go inside another block
{
var pi: i32 = 1234;
}
}
{#code_end#}
< p >
Because of this, when you read Zig code you can rely on an identifier always meaning the same thing,
within the scope it is defined. Note that you can, however use the same name if the scopes are separate:
< / p >
{#code_begin|test#}
test "separate scopes" {
{
const pi = 3.14;
}
{
var pi: bool = true;
}
}
{#code_end#}
2018-08-28 01:59:28 +01:00
{#header_close#}
2019-02-18 22:49:26 +00:00
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|switch#}
2018-01-19 08:03:20 +00:00
{#code_begin|test|switch#}
2020-02-27 19:41:44 +00:00
const std = @import("std");
const assert = std.debug.assert;
2017-11-07 08:22:27 +00:00
test "switch simple" {
const a: u64 = 10;
const zz: u64 = 103;
// All branches of a switch expression must be able to be coerced to a
// common type.
//
// Branches cannot fallthrough. If fallthrough behavior is desired, combine
// the cases and use an if.
const b = switch (a) {
// Multiple cases can be combined via a ','
2018-01-19 08:03:20 +00:00
1, 2, 3 => 0,
2017-11-07 08:22:27 +00:00
// Ranges can be specified using the ... syntax. These are inclusive
// both ends.
2019-02-27 03:46:35 +00:00
5...100 => 1,
2017-11-07 08:22:27 +00:00
// Branches can be arbitrarily complex.
2018-01-19 08:03:20 +00:00
101 => blk: {
2017-11-07 08:22:27 +00:00
const c: u64 = 5;
2018-01-19 08:03:20 +00:00
break :blk c * 2 + 1;
2017-11-07 08:22:27 +00:00
},
// Switching on arbitrary expressions is allowed as long as the
// expression is known at compile-time.
2018-01-19 08:03:20 +00:00
zz => zz,
comptime blk: {
2017-11-07 08:22:27 +00:00
const d: u32 = 5;
const e: u32 = 100;
2018-01-19 08:03:20 +00:00
break :blk d + e;
} => 107,
2017-11-07 08:22:27 +00:00
// The else branch catches everything not already captured.
// Else branches are mandatory unless the entire range of values
// is handled.
2018-01-19 08:03:20 +00:00
else => 9,
2017-11-07 08:22:27 +00:00
};
assert(b == 1);
}
2019-02-27 03:46:35 +00:00
// Switch expressions can be used outside a function:
2020-02-27 19:41:44 +00:00
const os_msg = switch (std.Target.current.os.tag) {
.linux => "we found a linux user",
2019-02-27 03:46:35 +00:00
else => "not a linux user",
};
// Inside a function, switch statements implicitly are compile-time
// evaluated if the target expression is compile-time known.
test "switch inside function" {
2020-02-27 19:41:44 +00:00
switch (std.Target.current.os.tag) {
.fuchsia => {
2019-02-27 03:46:35 +00:00
// On an OS other than fuchsia, block is not even analyzed,
// so this compile error is not triggered.
// On fuchsia this compile error would be triggered.
@compileError("fuchsia not supported");
},
else => {},
}
}
{#code_end#}
< p >
{#syntax#}switch{#endsyntax#} can be used to capture the field values
of a {#link|Tagged union#}. Modifications to the field values can be
done by placing a {#syntax#}*{#endsyntax#} before the capture variable name,
turning it into a pointer.
< / p >
{#code_begin|test#}
const assert = @import("std").debug.assert;
test "switch on tagged union" {
const Point = struct {
x: u8,
y: u8,
};
2018-11-13 13:08:37 +00:00
const Item = union(enum) {
2020-10-14 16:34:05 +01:00
a: u32,
c: Point,
d,
e: u32,
2017-11-07 08:22:27 +00:00
};
2020-10-14 16:34:05 +01:00
var a = Item{ .c = Point{ .x = 1, .y = 2 } };
2017-11-07 08:22:27 +00:00
// Switching on more complex enums is allowed.
const b = switch (a) {
// A capture group is allowed on a match, and will return the enum
2019-07-04 05:35:28 +01:00
// value matched. If the payload types of both cases are the same
2019-07-03 19:12:14 +01:00
// they can be put into the same switch prong.
2020-10-14 16:34:05 +01:00
Item.a, Item.e => |item| item,
2017-11-07 08:22:27 +00:00
// A reference to the matched value can be obtained using `*` syntax.
2020-10-14 16:34:05 +01:00
Item.c => |*item| blk: {
2018-05-18 04:21:44 +01:00
item.*.x += 1;
2018-01-19 08:03:20 +00:00
break :blk 6;
2017-11-07 08:22:27 +00:00
},
// No else is required if the types cases was exhaustively handled
2020-10-14 16:34:05 +01:00
Item.d => 8,
2017-11-07 08:22:27 +00:00
};
2019-02-27 03:46:35 +00:00
assert(b == 6);
2020-10-14 16:34:05 +01:00
assert(a.c.x == 2);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-01-17 05:22:33 +00:00
{#see_also|comptime|enum|@compileError|Compile Variables#}
2019-07-04 04:09:58 +01:00
{#header_open|Exhaustive Switching#}
< p >
When a {#syntax#}switch{#endsyntax#} expression does not have an {#syntax#}else{#endsyntax#} clause,
it must exhaustively list all the possible values. Failure to do so is a compile error:
< / p >
{#code_begin|test_err|not handled in switch#}
const Color = enum {
2020-10-14 16:34:05 +01:00
auto,
off,
on,
2019-07-04 04:09:58 +01:00
};
test "exhaustive switching" {
2020-10-14 16:34:05 +01:00
const color = Color.off;
2019-07-04 04:09:58 +01:00
switch (color) {
2020-10-14 16:34:05 +01:00
Color.auto => {},
Color.on => {},
2019-07-04 04:09:58 +01:00
}
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2019-07-04 04:09:58 +01:00
{#header_open|Switching with Enum Literals#}
< p >
{#link|Enum Literals#} can be useful to use with {#syntax#}switch{#endsyntax#} to avoid
repetitively specifying {#link|enum#} or {#link|union#} types:
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
const Color = enum {
2020-10-14 16:34:05 +01:00
auto,
off,
on,
2019-07-04 04:09:58 +01:00
};
test "enum literals with switch" {
2020-10-14 16:34:05 +01:00
const color = Color.off;
2019-07-04 04:09:58 +01:00
const result = switch (color) {
2020-10-14 16:34:05 +01:00
.auto => false,
.on => false,
.off => true,
2019-07-04 04:09:58 +01:00
};
assert(result);
}
{#code_end#}
{#header_close#}
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|while#}
2018-07-03 19:03:27 +01:00
< p >
A while loop is used to repeatedly execute an expression until
some condition is no longer true.
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test|while#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
test "while basic" {
var i: usize = 0;
2018-01-19 08:03:20 +00:00
while (i < 10 ) {
2017-11-07 08:22:27 +00:00
i += 1;
}
assert(i == 10);
}
2018-07-03 19:03:27 +01:00
{#code_end#}
< p >
2018-09-14 15:35:03 +01:00
Use {#syntax#}break{#endsyntax#} to exit a while loop early.
2018-07-03 19:03:27 +01:00
< / p >
{#code_begin|test|while#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
test "while break" {
var i: usize = 0;
while (true) {
if (i == 10)
break;
i += 1;
}
assert(i == 10);
}
2018-07-03 19:03:27 +01:00
{#code_end#}
< p >
2018-09-14 15:35:03 +01:00
Use {#syntax#}continue{#endsyntax#} to jump back to the beginning of the loop.
2018-07-03 19:03:27 +01:00
< / p >
{#code_begin|test|while#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
test "while continue" {
var i: usize = 0;
while (true) {
i += 1;
2018-01-19 08:03:20 +00:00
if (i < 10 )
2017-11-07 08:22:27 +00:00
continue;
break;
}
assert(i == 10);
}
2018-07-03 19:03:27 +01:00
{#code_end#}
< p >
While loops support a continue expression which is executed when the loop
2018-09-14 15:35:03 +01:00
is continued. The {#syntax#}continue{#endsyntax#} keyword respects this expression.
2018-07-03 19:03:27 +01:00
< / p >
{#code_begin|test|while#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
2018-07-14 16:52:48 +01:00
test "while loop continue expression" {
2017-11-07 08:22:27 +00:00
var i: usize = 0;
2018-01-19 08:03:20 +00:00
while (i < 10 ) : ( i + = 1 ) { }
2017-11-07 08:22:27 +00:00
assert(i == 10);
}
2018-07-14 16:52:48 +01:00
test "while loop continue expression, more complicated" {
2018-07-16 15:53:15 +01:00
var i: usize = 1;
var j: usize = 1;
while (i * j < 2000 ) : ( { i * = 2 ; j * = 3 ; } ) {
const my_ij = i * j;
assert(my_ij < 2000 ) ;
2017-11-07 08:22:27 +00:00
}
}
2018-07-03 19:03:27 +01:00
{#code_end#}
< p >
While loops are expressions. The result of the expression is the
2018-09-14 15:35:03 +01:00
result of the {#syntax#}else{#endsyntax#} clause of a while loop, which is executed when
2018-07-03 19:03:27 +01:00
the condition of the while loop is tested as false.
< / p >
< p >
2018-09-14 15:35:03 +01:00
{#syntax#}break{#endsyntax#}, like {#syntax#}return{#endsyntax#}, accepts a value
parameter. This is the result of the {#syntax#}while{#endsyntax#} expression.
When you {#syntax#}break{#endsyntax#} from a while loop, the {#syntax#}else{#endsyntax#} branch is not
2018-07-03 19:03:27 +01:00
evaluated.
< / p >
{#code_begin|test|while#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
test "while else" {
assert(rangeHasNumber(0, 10, 5));
assert(!rangeHasNumber(0, 10, 15));
}
2018-01-25 09:10:11 +00:00
fn rangeHasNumber(begin: usize, end: usize, number: usize) bool {
2017-11-07 08:22:27 +00:00
var i = begin;
2018-01-19 08:03:20 +00:00
return while (i < end ) : ( i + = 1 ) {
2017-11-07 08:22:27 +00:00
if (i == number) {
break true;
}
2018-01-19 08:03:20 +00:00
} else false;
2017-11-07 08:22:27 +00:00
}
2018-07-03 19:03:27 +01:00
{#code_end#}
2018-08-28 01:59:28 +01:00
{#header_open|Labeled while#}
2018-09-14 15:35:03 +01:00
< p > When a {#syntax#}while{#endsyntax#} loop is labeled, it can be referenced from a {#syntax#}break{#endsyntax#}
or {#syntax#}continue{#endsyntax#} from within a nested loop:< / p >
2018-08-28 01:59:28 +01:00
{#code_begin|test#}
test "nested break" {
outer: while (true) {
while (true) {
break :outer;
}
}
}
test "nested continue" {
var i: usize = 0;
outer: while (i < 10 ) : ( i + = 1 ) {
while (true) {
continue :outer;
}
}
}
{#code_end#}
{#header_close#}
2018-07-03 19:03:27 +01:00
{#header_open|while with Optionals#}
< p >
Just like {#link|if#} expressions, while loops can take an optional as the
condition and capture the payload. When {#link|null#} is encountered the loop
exits.
< / p >
< p >
2018-09-14 15:35:03 +01:00
When the {#syntax#}|x|{#endsyntax#} syntax is present on a {#syntax#}while{#endsyntax#} expression,
2018-07-03 19:03:27 +01:00
the while condition must have an {#link|Optional Type#}.
< / p >
< p >
2018-09-14 15:35:03 +01:00
The {#syntax#}else{#endsyntax#} branch is allowed on optional iteration. In this case, it will
2018-07-03 19:03:27 +01:00
be executed on the first null value encountered.
< / p >
{#code_begin|test|while#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
test "while null capture" {
var sum1: u32 = 0;
numbers_left = 3;
while (eventuallyNullSequence()) |value| {
sum1 += value;
}
assert(sum1 == 3);
var sum2: u32 = 0;
numbers_left = 3;
while (eventuallyNullSequence()) |value| {
sum2 += value;
} else {
2019-04-18 18:32:44 +01:00
assert(sum2 == 3);
2017-11-07 08:22:27 +00:00
}
}
var numbers_left: u32 = undefined;
2018-01-25 09:10:11 +00:00
fn eventuallyNullSequence() ?u32 {
2018-01-19 08:03:20 +00:00
return if (numbers_left == 0) null else blk: {
2017-11-07 08:22:27 +00:00
numbers_left -= 1;
2018-01-19 08:03:20 +00:00
break :blk numbers_left;
};
2017-11-07 08:22:27 +00:00
}
2018-02-08 08:02:41 +00:00
2018-07-03 19:03:27 +01:00
{#code_end#}
{#header_close#}
{#header_open|while with Error Unions#}
< p >
Just like {#link|if#} expressions, while loops can take an error union as
the condition and capture the payload or the error code. When the
condition results in an error code the else branch is evaluated and
the loop is finished.
< / p >
< p >
2018-09-14 15:35:03 +01:00
When the {#syntax#}else |x|{#endsyntax#} syntax is present on a {#syntax#}while{#endsyntax#} expression,
2018-07-03 19:03:27 +01:00
the while condition must have an {#link|Error Union Type#}.
< / p >
{#code_begin|test|while#}
const assert = @import("std").debug.assert;
test "while error union capture" {
var sum1: u32 = 0;
numbers_left = 3;
while (eventuallyErrorSequence()) |value| {
sum1 += value;
} else |err| {
assert(err == error.ReachedZero);
}
}
var numbers_left: u32 = undefined;
2018-11-13 13:08:37 +00:00
fn eventuallyErrorSequence() anyerror!u32 {
2018-01-19 08:03:20 +00:00
return if (numbers_left == 0) error.ReachedZero else blk: {
2017-11-07 08:22:27 +00:00
numbers_left -= 1;
2018-01-19 08:03:20 +00:00
break :blk numbers_left;
};
2017-11-07 08:22:27 +00:00
}
2018-06-19 22:21:08 +01:00
{#code_end#}
2018-07-03 19:03:27 +01:00
{#header_close#}
2018-06-19 22:21:08 +01:00
{#header_open|inline while#}
< p >
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.
< / p >
{#code_begin|test#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
test "inline while loop" {
comptime var i = 0;
var sum: usize = 0;
2018-01-19 08:03:20 +00:00
inline while (i < 3 ) : ( i + = 1 ) {
2017-11-07 08:22:27 +00:00
const T = switch (i) {
2018-01-19 08:03:20 +00:00
0 => f32,
1 => i8,
2 => bool,
else => unreachable,
2017-11-07 08:22:27 +00:00
};
sum += typeNameLength(T);
}
assert(sum == 9);
}
2018-01-25 09:10:11 +00:00
fn typeNameLength(comptime T: type) usize {
2017-11-07 08:22:27 +00:00
return @typeName(T).len;
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-06-19 22:21:08 +01:00
< p >
2018-09-14 15:35:03 +01:00
It is recommended to use {#syntax#}inline{#endsyntax#} loops only for one of these reasons:
2018-06-19 22:21:08 +01:00
< / p >
< ul >
< li > You need the loop to execute at {#link|comptime#} for the semantics to work.< / li >
< li >
You have a benchmark to prove that forcibly unrolling the loop in this way is measurably faster.
< / li >
< / ul >
{#header_close#}
2018-06-10 04:42:14 +01:00
{#see_also|if|Optionals|Errors|comptime|unreachable#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|for#}
2018-01-19 08:03:20 +00:00
{#code_begin|test|for#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
test "for basics" {
2019-06-10 00:24:24 +01:00
const items = [_]i32 { 4, 5, 3, 4, 0 };
2017-11-07 08:22:27 +00:00
var sum: i32 = 0;
// For loops iterate over slices and arrays.
for (items) |value| {
// Break and continue are supported.
if (value == 0) {
continue;
}
sum += value;
}
assert(sum == 16);
// To iterate over a portion of a slice, reslice.
for (items[0..1]) |value| {
sum += value;
}
assert(sum == 20);
// To access the index of iteration, specify a second capture value.
// This is zero-indexed.
var sum2: i32 = 0;
for (items) |value, i| {
2019-12-09 20:59:42 +00:00
assert(@TypeOf(i) == usize);
2018-06-17 07:57:07 +01:00
sum2 += @intCast(i32, i);
2017-11-07 08:22:27 +00:00
}
assert(sum2 == 10);
}
test "for reference" {
2019-06-10 00:24:24 +01:00
var items = [_]i32 { 3, 4, 2 };
2017-11-07 08:22:27 +00:00
// Iterate over the slice by reference by
// specifying that the capture value is a pointer.
for (items) |*value| {
2018-05-18 04:21:44 +01:00
value.* += 1;
2017-11-07 08:22:27 +00:00
}
assert(items[0] == 4);
assert(items[1] == 5);
assert(items[2] == 3);
}
test "for else" {
// For allows an else attached to it, the same as a while loop.
2019-06-10 00:24:24 +01:00
var items = [_]?i32 { 3, 4, null, 5 };
2017-11-07 08:22:27 +00:00
// For loops can also be used as expressions.
2019-06-08 20:49:56 +01:00
// Similar to while loops, when you break from a for loop, the else branch is not evaluated.
2017-11-07 08:22:27 +00:00
var sum: i32 = 0;
const result = for (items) |value| {
2019-06-09 00:43:05 +01:00
if (value != null) {
2018-06-10 04:42:14 +01:00
sum += value.?;
2017-11-07 08:22:27 +00:00
}
2018-01-19 08:03:20 +00:00
} else blk: {
2019-06-09 00:43:05 +01:00
assert(sum == 12);
2018-01-19 08:03:20 +00:00
break :blk sum;
2017-11-07 08:22:27 +00:00
};
2019-06-09 00:43:05 +01:00
assert(result == 12);
2017-11-07 08:22:27 +00:00
}
2018-06-19 22:21:08 +01:00
{#code_end#}
2018-08-28 01:59:28 +01:00
{#header_open|Labeled for#}
2018-09-14 15:35:03 +01:00
< p > When a {#syntax#}for{#endsyntax#} loop is labeled, it can be referenced from a {#syntax#}break{#endsyntax#}
or {#syntax#}continue{#endsyntax#} from within a nested loop:< / p >
2018-08-28 01:59:28 +01:00
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
test "nested break" {
var count: usize = 0;
2019-06-10 00:24:24 +01:00
outer: for ([_]i32{ 1, 2, 3, 4, 5 }) |_| {
for ([_]i32{ 1, 2, 3, 4, 5 }) |_| {
2018-08-28 01:59:28 +01:00
count += 1;
break :outer;
}
}
assert(count == 1);
}
test "nested continue" {
var count: usize = 0;
2019-06-10 00:24:24 +01:00
outer: for ([_]i32{ 1, 2, 3, 4, 5, 6, 7, 8 }) |_| {
for ([_]i32{ 1, 2, 3, 4, 5 }) |_| {
2018-08-28 01:59:28 +01:00
count += 1;
continue :outer;
}
}
assert(count == 8);
}
{#code_end#}
{#header_close#}
2018-06-19 22:21:08 +01:00
{#header_open|inline for#}
< p >
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.
< / p >
{#code_begin|test#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
test "inline for loop" {
2019-06-10 00:24:24 +01:00
const nums = [_]i32{2, 4, 6};
2017-11-07 08:22:27 +00:00
var sum: usize = 0;
inline for (nums) |i| {
const T = switch (i) {
2018-01-19 08:03:20 +00:00
2 => f32,
4 => i8,
6 => bool,
else => unreachable,
2017-11-07 08:22:27 +00:00
};
sum += typeNameLength(T);
}
assert(sum == 9);
}
2018-01-25 09:10:11 +00:00
fn typeNameLength(comptime T: type) usize {
2017-11-07 08:22:27 +00:00
return @typeName(T).len;
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-06-19 22:21:08 +01:00
< p >
2018-09-14 15:35:03 +01:00
It is recommended to use {#syntax#}inline{#endsyntax#} loops only for one of these reasons:
2018-06-19 22:21:08 +01:00
< / p >
< ul >
< li > You need the loop to execute at {#link|comptime#} for the semantics to work.< / li >
< li >
You have a benchmark to prove that forcibly unrolling the loop in this way is measurably faster.
< / li >
< / ul >
{#header_close#}
2018-01-17 05:22:33 +00:00
{#see_also|while|comptime|Arrays|Slices#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|if#}
2018-01-19 08:03:20 +00:00
{#code_begin|test|if#}
// If expressions have three uses, corresponding to the three types:
2017-11-07 08:22:27 +00:00
// * bool
// * ?T
2018-11-13 13:08:37 +00:00
// * anyerror!T
2017-11-07 08:22:27 +00:00
const assert = @import("std").debug.assert;
2019-12-28 15:59:47 +00:00
test "if expression" {
// If expressions are used instead of a ternary expression.
const a: u32 = 5;
const b: u32 = 4;
const result = if (a != b) 47 else 3089;
assert(result == 47);
}
2017-11-07 08:22:27 +00:00
test "if boolean" {
// If expressions test boolean conditions.
const a: u32 = 5;
const b: u32 = 4;
if (a != b) {
assert(true);
} else if (a == 9) {
2018-01-19 08:03:20 +00:00
unreachable;
2017-11-07 08:22:27 +00:00
} else {
2018-01-19 08:03:20 +00:00
unreachable;
2017-11-07 08:22:27 +00:00
}
}
2018-06-10 04:42:14 +01:00
test "if optional" {
2017-11-07 08:22:27 +00:00
// If expressions test for null.
const a: ?u32 = 0;
if (a) |value| {
assert(value == 0);
} else {
unreachable;
}
const b: ?u32 = null;
if (b) |value| {
unreachable;
} else {
assert(true);
}
// The else is not required.
if (a) |value| {
assert(value == 0);
}
// To test against null only, use the binary equality operator.
if (b == null) {
assert(true);
}
// Access the value by reference using a pointer capture.
var c: ?u32 = 3;
if (c) |*value| {
2018-05-18 04:21:44 +01:00
value.* = 2;
2017-11-07 08:22:27 +00:00
}
if (c) |value| {
assert(value == 2);
} else {
unreachable;
}
}
test "if error union" {
// If expressions test for errors.
// Note the |err| capture on the else.
2018-11-13 13:08:37 +00:00
const a: anyerror!u32 = 0;
2017-11-07 08:22:27 +00:00
if (a) |value| {
assert(value == 0);
} else |err| {
2018-01-19 08:03:20 +00:00
unreachable;
2017-11-07 08:22:27 +00:00
}
2018-11-13 13:08:37 +00:00
const b: anyerror!u32 = error.BadValue;
2017-11-07 08:22:27 +00:00
if (b) |value| {
2018-01-19 08:03:20 +00:00
unreachable;
2017-11-07 08:22:27 +00:00
} else |err| {
assert(err == error.BadValue);
}
// The else and |err| capture is strictly required.
if (a) |value| {
assert(value == 0);
} else |_| {}
// To check only the error value, use an empty block expression.
if (b) |_| {} else |err| {
assert(err == error.BadValue);
}
// Access the value by reference using a pointer capture.
2018-11-13 13:08:37 +00:00
var c: anyerror!u32 = 3;
2017-11-07 08:22:27 +00:00
if (c) |*value| {
2018-05-18 04:21:44 +01:00
value.* = 9;
2017-11-07 08:22:27 +00:00
} else |err| {
2018-01-19 08:03:20 +00:00
unreachable;
2017-11-07 08:22:27 +00:00
}
if (c) |value| {
assert(value == 9);
} else |err| {
2018-01-19 08:03:20 +00:00
unreachable;
2017-11-07 08:22:27 +00:00
}
2018-01-19 08:03:20 +00:00
}
2020-07-08 08:53:19 +01:00
test "if error union with optional" {
// If expressions test for errors before unwrapping optionals.
// The |optional_value| capture's type is ?u32.
const a: anyerror!?u32 = 0;
if (a) |optional_value| {
assert(optional_value.? == 0);
} else |err| {
unreachable;
}
const b: anyerror!?u32 = null;
if (b) |optional_value| {
assert(optional_value == null);
} else |err| {
unreachable;
}
const c: anyerror!?u32 = error.BadValue;
if (c) |optional_value| {
unreachable;
} else |err| {
assert(err == error.BadValue);
}
2020-07-08 21:40:16 +01:00
// Access the value by reference by using a pointer capture each time.
var d: anyerror!?u32 = 3;
if (d) |*optional_value| {
if (optional_value.*) |*value| {
value.* = 9;
}
} else |err| {
unreachable;
}
if (d) |optional_value| {
assert(optional_value.? == 9);
} else |err| {
unreachable;
}
2020-07-08 08:53:19 +01:00
}
2018-01-19 08:03:20 +00:00
{#code_end#}
2018-06-10 04:42:14 +01:00
{#see_also|Optionals|Errors#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-01-17 05:22:33 +00:00
{#header_open|defer#}
2018-01-19 08:03:20 +00:00
{#code_begin|test|defer#}
const std = @import("std");
const assert = std.debug.assert;
2020-06-19 10:38:22 +01:00
const print = std.debug.print;
2017-11-07 08:22:27 +00:00
// defer will execute an expression at the end of the current scope.
2018-01-25 09:10:11 +00:00
fn deferExample() usize {
2017-11-07 08:22:27 +00:00
var a: usize = 1;
{
defer a = 2;
a = 1;
}
assert(a == 2);
a = 5;
2018-01-19 08:03:20 +00:00
return a;
2017-11-07 08:22:27 +00:00
}
test "defer basics" {
assert(deferExample() == 5);
}
// If multiple defer statements are specified, they will be executed in
// the reverse order they were run.
2018-01-25 09:10:11 +00:00
fn deferUnwindExample() void {
2020-06-19 10:38:22 +01:00
print("\n", .{});
2017-11-07 08:22:27 +00:00
defer {
2020-06-19 10:38:22 +01:00
print("1 ", .{});
2017-11-07 08:22:27 +00:00
}
defer {
2020-06-19 10:38:22 +01:00
print("2 ", .{});
2017-11-07 08:22:27 +00:00
}
if (false) {
// defers are not run if they are never executed.
defer {
2020-06-19 10:38:22 +01:00
print("3 ", .{});
2017-11-07 08:22:27 +00:00
}
}
}
test "defer unwinding" {
2018-01-19 08:03:20 +00:00
deferUnwindExample();
2017-11-07 08:22:27 +00:00
}
2018-01-24 04:08:09 +00:00
// The errdefer keyword is similar to defer, but will only execute if the
2017-11-07 08:22:27 +00:00
// scope returns with an error.
//
// This is especially useful in allowing a function to clean up properly
// on error, and replaces goto error handling tactics as seen in c.
2018-02-08 08:02:41 +00:00
fn deferErrorExample(is_error: bool) !void {
2020-06-19 10:38:22 +01:00
print("\nstart of function\n", .{});
2017-11-07 08:22:27 +00:00
// This will always be executed on exit
defer {
2020-06-19 10:38:22 +01:00
print("end of function\n", .{});
2017-11-07 08:22:27 +00:00
}
2018-01-24 04:08:09 +00:00
errdefer {
2020-06-19 10:38:22 +01:00
print("encountered an error!\n", .{});
2017-11-07 08:22:27 +00:00
}
if (is_error) {
return error.DeferError;
}
}
2018-01-24 04:08:09 +00:00
test "errdefer unwinding" {
2019-03-23 23:33:00 +00:00
deferErrorExample(false) catch {};
deferErrorExample(true) catch {};
2017-11-07 08:22:27 +00:00
}
2018-01-19 08:03:20 +00:00
{#code_end#}
2018-01-17 05:22:33 +00:00
{#see_also|Errors#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|unreachable#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
In {#syntax#}Debug{#endsyntax#} and {#syntax#}ReleaseSafe{#endsyntax#} mode, and when using < code > zig test< / code > ,
{#syntax#}unreachable{#endsyntax#} emits a call to {#syntax#}panic{#endsyntax#} with the message < code > reached unreachable code< / code > .
2017-11-07 08:22:27 +00:00
< / p >
< p >
2018-09-14 15:35:03 +01:00
In {#syntax#}ReleaseFast{#endsyntax#} mode, the optimizer uses the assumption that {#syntax#}unreachable{#endsyntax#} code
will never be hit to perform optimizations. However, < code > zig test< / code > even in {#syntax#}ReleaseFast{#endsyntax#} mode
still emits {#syntax#}unreachable{#endsyntax#} as calls to {#syntax#}panic{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 04:19:05 +00:00
{#header_open|Basics#}
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
// unreachable is used to assert that control flow will never happen upon a
2017-11-07 08:22:27 +00:00
// particular location:
test "basic math" {
const x = 1;
const y = 2;
if (x + y != 3) {
unreachable;
}
}
2018-01-19 08:03:20 +00:00
{#code_end#}
< p > In fact, this is how assert is implemented:< / p >
{#code_begin|test_err#}
2018-01-25 09:10:11 +00:00
fn assert(ok: bool) void {
2017-11-07 08:22:27 +00:00
if (!ok) unreachable; // assertion failure
}
// This test will fail because we hit unreachable.
test "this will fail" {
assert(false);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|At Compile-Time#}
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|unreachable code#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
2018-01-19 08:03:20 +00:00
test "type of unreachable" {
comptime {
// The type of unreachable is noreturn.
2017-11-07 08:22:27 +00:00
2018-01-19 08:03:20 +00:00
// However this assertion will still fail because
// evaluating unreachable at compile-time is a compile error.
2017-11-07 08:22:27 +00:00
2019-12-09 20:59:42 +00:00
assert(@TypeOf(unreachable) == noreturn);
2018-01-19 08:03:20 +00:00
}
}
{#code_end#}
2018-01-17 05:22:33 +00:00
{#see_also|Zig Test|Build Mode|comptime#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_close#}
{#header_open|noreturn#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
{#syntax#}noreturn{#endsyntax#} is the type of:
2017-11-07 08:22:27 +00:00
< / p >
< ul >
2018-09-14 15:35:03 +01:00
< li > {#syntax#}break{#endsyntax#}< / li >
< li > {#syntax#}continue{#endsyntax#}< / li >
< li > {#syntax#}return{#endsyntax#}< / li >
< li > {#syntax#}unreachable{#endsyntax#}< / li >
< li > {#syntax#}while (true) {}{#endsyntax#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
2018-09-14 15:35:03 +01:00
< p > When resolving types together, such as {#syntax#}if{#endsyntax#} clauses or {#syntax#}switch{#endsyntax#} prongs,
the {#syntax#}noreturn{#endsyntax#} type is compatible with every other type. Consider:
2017-11-07 08:22:27 +00:00
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
2018-01-25 09:10:11 +00:00
fn foo(condition: bool, b: u32) void {
2017-11-07 08:22:27 +00:00
const a = if (condition) b else return;
2018-01-19 08:03:20 +00:00
@panic("do something with a");
2017-11-07 08:22:27 +00:00
}
2018-01-19 08:03:20 +00:00
test "noreturn" {
foo(false, 1);
}
{#code_end#}
2018-09-14 15:35:03 +01:00
< p > Another use case for {#syntax#}noreturn{#endsyntax#} is the {#syntax#}exit{#endsyntax#} function:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
{#target_windows#}
2020-01-06 23:26:15 +00:00
pub extern "kernel32" fn ExitProcess(exit_code: c_uint) callconv(.Stdcall) noreturn;
2017-11-07 08:22:27 +00:00
2018-01-19 08:03:20 +00:00
test "foo" {
2018-01-07 22:28:20 +00:00
const value = bar() catch ExitProcess(1);
2017-11-07 08:22:27 +00:00
assert(value == 1234);
}
2018-11-13 13:08:37 +00:00
fn bar() anyerror!u32 {
2017-11-07 08:22:27 +00:00
return 1234;
}
2018-01-19 08:03:20 +00:00
const assert = @import("std").debug.assert;
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Functions#}
2018-01-19 08:03:20 +00:00
{#code_begin|test|functions#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
// Functions are declared like this
2018-01-25 09:10:11 +00:00
fn add(a: i8, b: i8) i8 {
2017-11-07 08:22:27 +00:00
if (a == 0) {
return b;
}
2017-12-22 05:50:30 +00:00
return a + b;
2017-11-07 08:22:27 +00:00
}
// The export specifier makes a function externally visible in the generated
// object file, and makes it use the C ABI.
2018-01-25 09:10:11 +00:00
export fn sub(a: i8, b: i8) i8 { return a - b; }
2017-11-07 08:22:27 +00:00
// The extern specifier is used to declare a function that will be resolved
// at link time, when linking statically, or at runtime, when linking
// dynamically.
2020-01-06 23:26:15 +00:00
// The callconv specifier changes the calling convention of the function.
extern "kernel32" fn ExitProcess(exit_code: u32) callconv(.Stdcall) noreturn;
2018-01-25 09:10:11 +00:00
extern "c" fn atan2(a: f64, b: f64) f64;
2017-11-07 08:22:27 +00:00
2018-01-23 03:24:07 +00:00
// The @setCold builtin tells the optimizer that a function is rarely called.
2018-01-25 09:10:11 +00:00
fn abort() noreturn {
2018-01-23 03:24:07 +00:00
@setCold(true);
2017-11-07 08:22:27 +00:00
while (true) {}
}
2020-01-06 23:26:15 +00:00
// The naked calling convention makes a function not have any function prologue or epilogue.
2017-11-07 08:22:27 +00:00
// This can be useful when integrating with assembly.
2020-01-06 23:26:15 +00:00
fn _start() callconv(.Naked) noreturn {
2017-11-07 08:22:27 +00:00
abort();
}
2019-02-18 22:53:41 +00:00
// The inline specifier forces a function to be inlined at all call sites.
// If the function cannot be inlined, it is a compile-time error.
inline fn shiftLeftOne(a: u32) u32 {
return a < < 1 ;
}
2017-11-07 08:22:27 +00:00
// The pub specifier allows the function to be visible when importing.
// Another file can use @import and call sub2
2018-01-25 09:10:11 +00:00
pub fn sub2(a: i8, b: i8) i8 { return a - b; }
2017-11-07 08:22:27 +00:00
// Functions can be used as values and are equivalent to pointers.
2018-01-25 09:10:11 +00:00
const call2_op = fn (a: i8, b: i8) i8;
fn do_op(fn_call: call2_op, op1: i8, op2: i8) i8 {
2018-01-19 08:03:20 +00:00
return fn_call(op1, op2);
2017-11-07 08:22:27 +00:00
}
test "function" {
assert(do_op(add, 5, 6) == 11);
assert(do_op(sub2, 5, 6) == -1);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p > Function values are like pointers:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|obj#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
comptime {
2019-12-09 20:59:42 +00:00
assert(@TypeOf(foo) == fn()void);
2018-01-25 09:10:11 +00:00
assert(@sizeOf(fn()void) == @sizeOf(?fn()void));
2017-11-07 08:22:27 +00:00
}
2018-01-25 09:10:11 +00:00
fn foo() void { }
2018-01-19 08:03:20 +00:00
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_open|Pass-by-value Parameters#}
2017-11-07 08:22:27 +00:00
< p >
2019-02-05 15:28:05 +00:00
Primitive types such as {#link|Integers#} and {#link|Floats#} passed as parameters
are copied, and then the copy is available in the function body. This is called "passing by value".
Copying a primitive type is essentially free and typically involves nothing more than
setting a register.
< / p >
< p >
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.
2017-11-07 08:22:27 +00:00
< / p >
2018-06-14 03:40:38 +01:00
{#code_begin|test#}
2018-11-13 13:08:37 +00:00
const Point = struct {
2017-11-07 08:22:27 +00:00
x: i32,
2018-06-14 03:40:38 +01:00
y: i32,
2017-11-07 08:22:27 +00:00
};
2018-06-14 03:40:38 +01:00
fn foo(point: Point) i32 {
2019-02-05 15:28:05 +00:00
// Here, `point` could be a reference, or a copy. The function body
// can ignore the difference and treat it as a value. Be very careful
// taking the address of the parameter - it should be treated as if
// the address will become invalid when the function returns.
2018-06-14 03:40:38 +01:00
return point.x + point.y;
2018-01-19 08:03:20 +00:00
}
2017-11-07 08:22:27 +00:00
2018-06-14 03:40:38 +01:00
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
2019-02-05 15:28:05 +00:00
test "pass struct to function" {
2018-11-13 13:08:37 +00:00
assert(foo(Point{ .x = 1, .y = 2 }) == 3);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-06-14 03:40:38 +01:00
For extern functions, Zig follows the C ABI for passing structs and unions by value.
2017-11-07 08:22:27 +00:00
< / p >
2019-10-11 09:41:21 +01:00
{#header_close#}
{#header_open|Function Parameter Type Inference#}
2019-12-09 20:59:42 +00:00
< p >
2020-07-11 12:08:20 +01:00
Function parameters can be declared with {#syntax#}anytype{#endsyntax#} in place of the type.
2019-10-11 09:41:21 +01:00
In this case the parameter types will be inferred when the function is called.
2019-12-09 20:59:42 +00:00
Use {#link|@TypeOf#} and {#link|@typeInfo#} to get information about the inferred type.
2019-10-11 09:41:21 +01:00
< / p >
{#code_begin|test#}
const assert = @import("std").debug.assert;
2020-07-11 12:08:20 +01:00
fn addFortyTwo(x: anytype) @TypeOf(x) {
2019-10-11 09:41:21 +01:00
return x + 42;
}
test "fn type inference" {
assert(addFortyTwo(1) == 43);
2019-12-09 20:59:42 +00:00
assert(@TypeOf(addFortyTwo(1)) == comptime_int);
2019-10-11 09:41:21 +01:00
var y: i64 = 2;
assert(addFortyTwo(y) == 44);
2019-12-09 20:59:42 +00:00
assert(@TypeOf(addFortyTwo(y)) == i64);
2019-10-11 09:41:21 +01:00
}
{#code_end#}
2019-12-09 20:59:42 +00:00
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-01-31 16:47:56 +00:00
{#header_open|Function Reflection#}
{#code_begin|test#}
const assert = @import("std").debug.assert;
test "fn reflection" {
2020-09-04 20:49:14 +01:00
assert(@typeInfo(@TypeOf(assert)).Fn.return_type.? == void);
assert(@typeInfo(@TypeOf(assert)).Fn.is_var_args == false);
2018-01-31 16:47:56 +00:00
}
{#code_end#}
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Errors#}
2018-02-24 01:43:47 +00:00
{#header_open|Error Set Type#}
2017-11-07 08:22:27 +00:00
< p >
2018-02-24 01:43:47 +00:00
An error set is like an {#link|enum#}.
However, each error name across the entire compilation gets assigned an unsigned integer
greater than 0. You are allowed to declare the same error name more than once, and if you do, it
gets assigned the same integer value.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2018-02-24 01:43:47 +00:00
The number of unique error values across the entire compilation should determine the size of the error set type.
2018-09-14 15:35:03 +01:00
However right now it is hard coded to be a {#syntax#}u16{#endsyntax#}. See < a href = "https://github.com/ziglang/zig/issues/786" > #768< / a > .
2017-11-07 08:22:27 +00:00
< / p >
< p >
2019-11-08 20:56:21 +00:00
You can {#link|coerce|Type Coercion#} an error from a subset to a superset:
2017-11-07 08:22:27 +00:00
< / p >
2018-02-24 01:43:47 +00:00
{#code_begin|test#}
const std = @import("std");
2018-11-13 13:08:37 +00:00
const FileOpenError = error {
2018-02-24 01:43:47 +00:00
AccessDenied,
OutOfMemory,
FileNotFound,
};
2018-11-13 13:08:37 +00:00
const AllocationError = error {
2018-02-24 01:43:47 +00:00
OutOfMemory,
};
2019-11-08 20:56:21 +00:00
test "coerce subset to superset" {
2018-02-24 01:43:47 +00:00
const err = foo(AllocationError.OutOfMemory);
std.debug.assert(err == FileOpenError.OutOfMemory);
}
fn foo(err: AllocationError) FileOpenError {
return err;
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2019-11-08 20:56:21 +00:00
But you cannot {#link|coerce|Type Coercion#} an error from a superset to a subset:
2018-02-24 01:43:47 +00:00
< / p >
{#code_begin|test_err|not a member of destination error set#}
2018-11-13 13:08:37 +00:00
const FileOpenError = error {
2018-02-24 01:43:47 +00:00
AccessDenied,
OutOfMemory,
FileNotFound,
};
2018-11-13 13:08:37 +00:00
const AllocationError = error {
2018-02-24 01:43:47 +00:00
OutOfMemory,
};
2019-11-08 20:56:21 +00:00
test "coerce superset to subset" {
2018-02-24 01:43:47 +00:00
foo(FileOpenError.OutOfMemory) catch {};
}
fn foo(err: FileOpenError) AllocationError {
return err;
}
{#code_end#}
< p >
There is a shortcut for declaring an error set with only 1 value, and then getting that value:
< / p >
{#code_begin|syntax#}
const err = error.FileNotFound;
{#code_end#}
< p > This is equivalent to:< / p >
{#code_begin|syntax#}
2018-11-13 13:08:37 +00:00
const err = (error {FileNotFound}).FileNotFound;
2018-02-24 01:43:47 +00:00
{#code_end#}
< p >
This becomes useful when using {#link|Inferred Error Sets#}.
< / p >
{#header_open|The Global Error Set#}
2018-11-19 18:20:39 +00:00
< p > {#syntax#}anyerror{#endsyntax#} refers to the global error set.
2018-02-24 01:43:47 +00:00
This is the error set that contains all errors in the entire compilation unit.
It is a superset of all other error sets and a subset of none of them.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2019-11-08 20:56:21 +00:00
You can {#link|coerce|Type Coercion#} any error set to the global one, and you can explicitly
2018-11-19 18:20:39 +00:00
cast an error of the global error set to a non-global one. This inserts a language-level
2018-02-24 01:43:47 +00:00
assert to make sure the error value is in fact in the destination error set.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2018-03-25 23:48:07 +01:00
The global error set should generally be avoided because it prevents the
compiler from knowing what errors are possible at compile-time. Knowing
the error set at compile-time is better for generated documentation and
helpful error messages, such as forgetting a possible error value in a {#link|switch#}.
2017-11-07 08:22:27 +00:00
< / p >
2018-02-24 01:43:47 +00:00
{#header_close#}
{#header_close#}
{#header_open|Error Union Type#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
An error set type and normal type can be combined with the {#syntax#}!{#endsyntax#}
2018-03-25 23:48:07 +01:00
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.
2017-11-07 08:22:27 +00:00
< / p >
< p >
Here is a function to parse a string into a 64-bit integer:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
2018-10-26 19:59:58 +01:00
const std = @import("std");
const maxInt = std.math.maxInt;
2018-02-08 08:02:41 +00:00
pub fn parseU64(buf: []const u8, radix: u8) !u64 {
2017-11-07 08:22:27 +00:00
var x: u64 = 0;
for (buf) |c| {
const digit = charToDigit(c);
2018-01-19 08:03:20 +00:00
if (digit >= radix) {
2017-11-07 08:22:27 +00:00
return error.InvalidChar;
}
// x *= radix
2018-01-19 08:03:20 +00:00
if (@mulWithOverflow(u64, x, radix, & x)) {
2017-11-07 08:22:27 +00:00
return error.Overflow;
}
// x += digit
2018-01-19 08:03:20 +00:00
if (@addWithOverflow(u64, x, digit, & x)) {
2017-11-07 08:22:27 +00:00
return error.Overflow;
}
}
return x;
2018-01-19 08:03:20 +00:00
}
2018-01-25 09:10:11 +00:00
fn charToDigit(c: u8) u8 {
2018-01-19 08:03:20 +00:00
return switch (c) {
'0' ... '9' => c - '0',
'A' ... 'Z' => c - 'A' + 10,
'a' ... 'z' => c - 'a' + 10,
2018-10-26 19:59:58 +01:00
else => maxInt(u8),
2018-01-19 08:03:20 +00:00
};
}
test "parse u64" {
const result = try parseU64("1234", 10);
2018-10-26 19:59:58 +01:00
std.debug.assert(result == 1234);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
Notice the return type is {#syntax#}!u64{#endsyntax#}. This means that the function
2018-02-08 08:02:41 +00:00
either returns an unsigned 64 bit integer, or an error. We left off the error set
2018-09-14 15:35:03 +01:00
to the left of the {#syntax#}!{#endsyntax#}, so the error set is inferred.
2017-11-07 08:22:27 +00:00
< / p >
< p >
Within the function definition, you can see some return statements that return
2018-09-14 15:35:03 +01:00
an error, and at the bottom a return statement that returns a {#syntax#}u64{#endsyntax#}.
2019-11-08 20:56:21 +00:00
Both types {#link|coerce|Type Coercion#} to {#syntax#}anyerror!u64{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
< p >
What it looks like to use this function varies depending on what you're
trying to do. One of the following:
< / p >
< ul >
< li > You want to provide a default value if it returned an error.< / li >
< li > If it returned an error then you want to return the same error.< / li >
< li > You know with complete certainty it will not return an error, so want to unconditionally unwrap it.< / li >
< li > You want to take a different action for each possible error.< / li >
< / ul >
2018-06-14 23:12:05 +01:00
{#header_open|catch#}
2018-09-14 15:35:03 +01:00
< p > If you want to provide a default value, you can use the {#syntax#}catch{#endsyntax#} binary operator:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
2018-01-25 09:10:11 +00:00
fn doAThing(str: []u8) void {
2018-01-07 22:28:20 +00:00
const number = parseU64(str, 10) catch 13;
2017-11-07 08:22:27 +00:00
// ...
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
In this code, {#syntax#}number{#endsyntax#} will be equal to the successfully parsed string, or
a default value of 13. The type of the right hand side of the binary {#syntax#}catch{#endsyntax#} operator must
match the unwrapped error union type, or be of type {#syntax#}noreturn{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
2018-06-14 23:12:05 +01:00
{#header_close#}
{#header_open|try#}
2017-11-07 08:22:27 +00:00
< p > Let's say you wanted to return the error if you got one, otherwise continue with the
function logic:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
2018-02-08 08:02:41 +00:00
fn doAThing(str: []u8) !void {
2018-01-07 22:28:20 +00:00
const number = parseU64(str, 10) catch |err| return err;
2017-11-07 08:22:27 +00:00
// ...
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
There is a shortcut for this. The {#syntax#}try{#endsyntax#} expression:
2017-11-07 08:22:27 +00:00
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
2018-02-08 08:02:41 +00:00
fn doAThing(str: []u8) !void {
2018-01-07 21:51:46 +00:00
const number = try parseU64(str, 10);
2017-11-07 08:22:27 +00:00
// ...
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
{#syntax#}try{#endsyntax#} evaluates an error union expression. If it is an error, it returns
2017-11-07 08:22:27 +00:00
from the current function with the same error. Otherwise, the expression results in
the unwrapped value.
< / p >
2018-06-14 23:12:05 +01:00
{#header_close#}
2017-11-07 08:22:27 +00:00
< p >
Maybe you know with complete certainty that an expression will never be an error.
In this case you can do this:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}const number = parseU64("1234", 10) catch unreachable;{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
Here we know for sure that "1234" will parse successfully. So we put the
2018-09-14 15:35:03 +01:00
{#syntax#}unreachable{#endsyntax#} value on the right hand side. {#syntax#}unreachable{#endsyntax#} generates
2017-11-07 08:22:27 +00:00
a panic in Debug and ReleaseSafe modes and undefined behavior in ReleaseFast mode. So, while we're debugging the
application, if there < em > was< / em > a surprise error here, the application would crash
appropriately.
< / p >
< p >
Finally, you may want to take a different action for every situation. For that, we combine
2018-06-14 23:12:05 +01:00
the {#link|if#} and {#link|switch#} expression:
2017-11-07 08:22:27 +00:00
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
2018-01-25 09:10:11 +00:00
fn doAThing(str: []u8) void {
2017-11-07 08:22:27 +00:00
if (parseU64(str, 10)) |number| {
doSomethingWithNumber(number);
} else |err| switch (err) {
2018-01-19 08:03:20 +00:00
error.Overflow => {
2017-11-07 08:22:27 +00:00
// handle overflow...
},
// we promise that InvalidChar won't happen (or crash in debug mode if it does)
2018-01-19 08:03:20 +00:00
error.InvalidChar => unreachable,
2017-11-07 08:22:27 +00:00
}
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-06-14 23:12:05 +01:00
{#header_open|errdefer#}
2017-11-07 08:22:27 +00:00
< p >
The other component to error handling is defer statements.
2018-09-14 15:35:03 +01:00
In addition to an unconditional {#link|defer#}, Zig has {#syntax#}errdefer{#endsyntax#},
2017-11-07 08:22:27 +00:00
which evaluates the deferred expression on block exit path if and only if
the function returned with an error from the block.
< / p >
< p >
Example:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
2018-02-08 08:02:41 +00:00
fn createFoo(param: i32) !Foo {
2018-01-07 21:51:46 +00:00
const foo = try tryToAllocateFoo();
2017-11-07 08:22:27 +00:00
// now we have allocated foo. we need to free it if the function fails.
// but we want to return it if the function succeeds.
2018-01-24 04:08:09 +00:00
errdefer deallocateFoo(foo);
2017-11-07 08:22:27 +00:00
2018-06-10 06:13:51 +01:00
const tmp_buf = allocateTmpBuffer() orelse return error.OutOfMemory;
2017-11-07 08:22:27 +00:00
// tmp_buf is truly a temporary resource, and we for sure want to clean it up
// before this block leaves scope
defer deallocateTmpBuffer(tmp_buf);
2018-01-19 08:03:20 +00:00
if (param > 1337) return error.InvalidParam;
2017-11-07 08:22:27 +00:00
2018-01-24 04:08:09 +00:00
// here the errdefer will not run since we're returning success from the function.
2017-11-07 08:22:27 +00:00
// but the defer will run!
return foo;
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
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.
< / p >
2018-06-14 23:12:05 +01:00
{#header_close#}
2017-11-07 08:22:27 +00:00
< p >
A couple of other tidbits about error handling:
< / p >
< ul >
< li > These primitives give enough expressiveness that it's completely practical
to have failing to check for an error be a compile error. If you really want
2018-09-14 15:35:03 +01:00
to ignore the error, you can add {#syntax#}catch unreachable{#endsyntax#} and
2017-11-07 08:22:27 +00:00
get the added benefit of crashing in Debug and ReleaseSafe modes if your assumption was wrong.
< / li >
< li >
Since Zig understands error types, it can pre-weight branches in favor of
2018-11-16 18:33:58 +00:00
errors not occurring. Just a small optimization benefit that is not available
2017-11-07 08:22:27 +00:00
in other languages.
< / li >
< / ul >
2018-01-17 05:22:33 +00:00
{#see_also|defer|if|switch#}
2018-02-24 01:43:47 +00:00
2018-09-14 15:35:03 +01:00
< p > An error union is created with the {#syntax#}!{#endsyntax#} binary operator.
2018-01-31 16:47:56 +00:00
You can use compile-time reflection to access the child type of an error union:< / p >
{#code_begin|test#}
const assert = @import("std").debug.assert;
test "error union" {
2018-11-13 13:08:37 +00:00
var foo: anyerror!i32 = undefined;
2018-01-31 16:47:56 +00:00
2019-11-08 20:56:21 +00:00
// Coerce from child type of an error union:
2018-01-31 16:47:56 +00:00
foo = 1234;
2019-11-08 20:56:21 +00:00
// Coerce from an error set:
2018-01-31 16:47:56 +00:00
foo = error.SomeError;
2018-02-09 01:45:26 +00:00
// Use compile-time reflection to access the payload type of an error union:
2020-09-04 20:49:14 +01:00
comptime assert(@typeInfo(@TypeOf(foo)).ErrorUnion.payload == i32);
2018-02-09 01:45:26 +00:00
// Use compile-time reflection to access the error set type of an error union:
2020-09-04 20:49:14 +01:00
comptime assert(@typeInfo(@TypeOf(foo)).ErrorUnion.error_set == anyerror);
2018-01-31 16:47:56 +00:00
}
{#code_end#}
2018-06-13 00:38:59 +01:00
{#header_open|Merging Error Sets#}
< p >
2018-09-14 15:35:03 +01:00
Use the {#syntax#}||{#endsyntax#} operator to merge two error sets together. The resulting
2018-06-13 00:38:59 +01:00
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
2018-09-14 15:35:03 +01:00
comments for {#syntax#}C.PathNotFound{#endsyntax#} is < code > A doc comment< / code > .
2018-06-13 00:38:59 +01:00
< / p >
< p >
This is especially useful for functions which return different error sets depending
on {#link|comptime#} branches. For example, the Zig standard library uses
2018-09-14 15:35:03 +01:00
{#syntax#}LinuxFileOpenError || WindowsFileOpenError{#endsyntax#} for the error set of opening
2018-06-13 00:38:59 +01:00
files.
< / p >
{#code_begin|test#}
2018-11-13 13:08:37 +00:00
const A = error{
2018-06-13 00:38:59 +01:00
NotDir,
/// A doc comment
PathNotFound,
};
2018-11-13 13:08:37 +00:00
const B = error{
2018-06-13 00:38:59 +01:00
OutOfMemory,
/// B doc comment
PathNotFound,
};
const C = A || B;
fn foo() C!void {
return error.NotDir;
}
test "merge error sets" {
if (foo()) {
@panic("unexpected");
} else |err| switch (err) {
error.OutOfMemory => @panic("unexpected"),
error.PathNotFound => @panic("unexpected"),
error.NotDir => {},
}
}
{#code_end#}
{#header_close#}
2018-02-24 01:43:47 +00:00
{#header_open|Inferred Error Sets#}
2018-05-25 01:59:19 +01:00
< p >
Because many functions in Zig return a possible error, Zig supports inferring the error set.
To infer the error set for a function, use this syntax:
< / p >
{#code_begin|test#}
// With an inferred error set
pub fn add_inferred(comptime T: type, a: T, b: T) !T {
var answer: T = undefined;
return if (@addWithOverflow(T, a, b, & answer)) error.Overflow else answer;
2018-05-17 01:43:59 +01:00
}
2018-05-25 01:59:19 +01:00
// With an explicit error set
pub fn add_explicit(comptime T: type, a: T, b: T) Error!T {
var answer: T = undefined;
return if (@addWithOverflow(T, a, b, & answer)) error.Overflow else answer;
2018-05-17 01:43:59 +01:00
}
2018-11-13 13:08:37 +00:00
const Error = error {
2018-05-25 01:59:19 +01:00
Overflow,
2018-05-17 01:43:59 +01:00
};
2018-05-25 01:59:19 +01:00
const std = @import("std");
test "inferred error set" {
if (add_inferred(u8, 255, 1)) |_| unreachable else |err| switch (err) {
error.Overflow => {}, // ok
}
}
2018-05-17 01:43:59 +01:00
{#code_end#}
2018-05-25 01:59:19 +01:00
< p >
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.
< / p >
< p >
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.
< / p >
< p >
These limitations may be overcome in a future version of Zig.
< / p >
2018-01-31 16:47:56 +00:00
{#header_close#}
2018-02-24 01:43:47 +00:00
{#header_close#}
{#header_open|Error Return Traces#}
2018-06-14 23:12:05 +01:00
< p >
Error Return Traces show all the points in the code that an error was returned to the calling function. This makes it practical to use {#link|try#} everywhere and then still be able to know what happened if an error ends up bubbling all the way out of your application.
< / p >
{#code_begin|exe_err#}
pub fn main() !void {
try foo(12);
}
fn foo(x: i32) !void {
if (x >= 5) {
try bar();
} else {
try bang2();
}
}
fn bar() !void {
if (baz()) {
try quux();
} else |err| switch (err) {
error.FileNotFound => try hello(),
else => try another(),
}
}
fn baz() !void {
try bang1();
}
fn quux() !void {
try bang2();
}
fn hello() !void {
try bang2();
}
fn another() !void {
try bang1();
}
fn bang1() !void {
return error.FileNotFound;
}
fn bang2() !void {
return error.PermissionDenied;
}
{#code_end#}
< p >
Look closely at this example. This is no stack trace.
< / p >
< p >
2018-09-14 15:35:03 +01:00
You can see that the final error bubbled up was {#syntax#}PermissionDenied{#endsyntax#},
but the original error that started this whole thing was {#syntax#}FileNotFound{#endsyntax#}. In the {#syntax#}bar{#endsyntax#} function, the code handles the original error code,
2018-06-14 23:12:05 +01:00
and then returns another one, from the switch statement. Error Return Traces make this clear, whereas a stack trace would look like this:
< / p >
{#code_begin|exe_err#}
pub fn main() void {
foo(12);
}
fn foo(x: i32) void {
if (x >= 5) {
bar();
} else {
bang2();
}
}
fn bar() void {
if (baz()) {
quux();
} else {
hello();
}
}
fn baz() bool {
return bang1();
}
fn quux() void {
bang2();
}
fn hello() void {
bang2();
}
fn bang1() bool {
return false;
}
fn bang2() void {
@panic("PermissionDenied");
}
{#code_end#}
< p >
Here, the stack trace does not explain how the control
2018-09-14 15:35:03 +01:00
flow in {#syntax#}bar{#endsyntax#} got to the {#syntax#}hello(){#endsyntax#} call.
2018-06-14 23:12:05 +01:00
One would have to open a debugger or further instrument the application
2019-02-22 15:56:49 +00:00
in order to find out. The error return trace, on the other hand,
2018-06-14 23:12:05 +01:00
shows exactly how the error bubbled up.
< / p >
< p >
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.
< / p >
< p >
Error Return Traces are enabled by default in {#link|Debug#} and {#link|ReleaseSafe#} builds and disabled by default in {#link|ReleaseFast#} and {#link|ReleaseSmall#} builds.
< / p >
< p >
There are a few ways to activate this error return tracing feature:
< / p >
< ul >
< li > Return an error from main< / li >
2018-09-14 15:35:03 +01:00
< li > An error makes its way to {#syntax#}catch unreachable{#endsyntax#} and you have not overridden the default panic handler< / li >
< li > Use {#link|errorReturnTrace#} to access the current return trace. You can use {#syntax#}std.debug.dumpStackTrace{#endsyntax#} to print it. This function returns comptime-known {#link|null#} when building without error return tracing support.< / li >
2018-06-14 23:12:05 +01:00
< / ul >
{#header_open|Implementation Details#}
< p >
To analyze performance cost, there are two cases:
< / p >
< ul >
< li > when no errors are returned< / li >
< li > when returning errors< / li >
< / ul >
< p >
2018-11-13 13:08:37 +00:00
For the case when no errors are returned, the cost is a single memory write operation, only in the first non-failable function in the call graph that calls a failable function, i.e. when a function returning {#syntax#}void{#endsyntax#} calls a function returning {#syntax#}error{#endsyntax#}.
2018-06-14 23:12:05 +01:00
This is to initialize this struct in the stack memory:
< / p >
{#code_begin|syntax#}
2018-11-13 13:08:37 +00:00
pub const StackTrace = struct {
2018-06-14 23:12:05 +01:00
index: usize,
instruction_addresses: [N]usize,
};
{#code_end#}
< p >
Here, N is the maximum function call depth as determined by call graph analysis. Recursion is ignored and counts for 2.
< / p >
< p >
2018-09-14 15:35:03 +01:00
A pointer to {#syntax#}StackTrace{#endsyntax#} is passed as a secret parameter to every function that can return an error, but it's always the first parameter, so it can likely sit in a register and stay there.
2018-06-14 23:12:05 +01:00
< / p >
< p >
That's it for the path when no errors occur. It's practically free in terms of performance.
< / p >
< p >
2018-09-14 15:35:03 +01:00
When generating the code for a function that returns an error, just before the {#syntax#}return{#endsyntax#} statement (only for the {#syntax#}return{#endsyntax#} statements that return errors), Zig generates a call to this function:
2018-06-14 23:12:05 +01:00
< / p >
{#code_begin|syntax#}
// marked as "no-inline" in LLVM IR
fn __zig_return_error(stack_trace: *StackTrace) void {
stack_trace.instruction_addresses[stack_trace.index] = @returnAddress();
stack_trace.index = (stack_trace.index + 1) % N;
}
{#code_end#}
< p >
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.
< / p >
< p >
As for code size cost, 1 function call before a return statement is no big deal. Even so,
I have < a href = "https://github.com/ziglang/zig/issues/690" > a plan< / a > to make the call to
2018-11-13 13:08:37 +00:00
{#syntax#}__zig_return_error{#endsyntax#} a tail call, which brings the code size cost down to actually zero. What is a return statement in code without error return tracing can become a jump instruction in code with error return tracing.
2018-06-14 23:12:05 +01:00
< / p >
{#header_close#}
2018-01-31 16:47:56 +00:00
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-10 04:42:14 +01:00
{#header_open|Optionals#}
2017-11-07 08:22:27 +00:00
< p >
One area that Zig provides safety without compromising efficiency or
2018-06-10 04:42:14 +01:00
readability is with the optional type.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2018-06-10 04:42:14 +01:00
The question mark symbolizes the optional type. You can convert a type to an optional
2017-11-07 08:22:27 +00:00
type by putting a question mark in front of it, like this:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
// normal integer
2017-11-07 08:22:27 +00:00
const normal_int: i32 = 1234;
2018-06-10 04:42:14 +01:00
// optional integer
const optional_int: ?i32 = 5678;
2018-01-19 08:03:20 +00:00
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
Now the variable {#syntax#}optional_int{#endsyntax#} could be an {#syntax#}i32{#endsyntax#}, or {#syntax#}null{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
< p >
Instead of integers, let's talk about pointers. Null references are the source of many runtime
exceptions, and even stand accused of being
< a href = "https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/" > the worst mistake of computer science< / a > .
< / p >
< p > Zig does not have them.< / p >
< p >
2018-06-10 04:42:14 +01:00
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
2017-11-07 08:22:27 +00:00
can check your work and make sure you don't assign null to something that can't be null.
< / p >
< p >
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.
< / p >
< p >
Task: call malloc, if the result is null, return null.
< / p >
< p > C code< / p >
2018-01-19 08:03:20 +00:00
< pre > < code class = "cpp" > // malloc prototype included for reference
2017-11-07 08:22:27 +00:00
void *malloc(size_t size);
struct Foo *do_a_thing(void) {
char *ptr = malloc(1234);
if (!ptr) return NULL;
// ...
}< / code > < / pre >
< p > Zig code< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
// malloc prototype included for reference
2018-05-31 15:56:59 +01:00
extern fn malloc(size: size_t) ?*u8;
2017-11-07 08:22:27 +00:00
2018-05-31 15:56:59 +01:00
fn doAThing() ?*Foo {
2018-06-10 06:13:51 +01:00
const ptr = malloc(1234) orelse return null;
2017-11-07 08:22:27 +00:00
// ...
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
Here, Zig is at least as convenient, if not more, than C. And, the type of "ptr"
2018-09-14 15:35:03 +01:00
is {#syntax#}*u8{#endsyntax#} < em > not< / em > {#syntax#}?*u8{#endsyntax#}. The {#syntax#}orelse{#endsyntax#} keyword
unwrapped the optional type and therefore {#syntax#}ptr{#endsyntax#} is guaranteed to be non-null everywhere
2017-11-07 08:22:27 +00:00
it is used in the function.
< / p >
< p >
The other form of checking against NULL you might see looks like this:
< / p >
2018-01-19 08:03:20 +00:00
< pre > < code class = "cpp" > void do_a_thing(struct Foo *foo) {
2017-11-07 08:22:27 +00:00
// do some stuff
if (foo) {
do_something_with_foo(foo);
}
// do some stuff
}< / code > < / pre >
< p >
In Zig you can accomplish the same thing:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
2018-06-10 04:42:14 +01:00
fn doAThing(optional_foo: ?*Foo) void {
2017-11-07 08:22:27 +00:00
// do some stuff
2018-06-10 04:42:14 +01:00
if (optional_foo) |foo| {
2017-11-07 08:22:27 +00:00
doSomethingWithFoo(foo);
}
// do some stuff
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
Once again, the notable thing here is that inside the if block,
2018-09-14 15:35:03 +01:00
{#syntax#}foo{#endsyntax#} is no longer an optional pointer, it is a pointer, which
2017-11-07 08:22:27 +00:00
cannot be null.
< / p >
< p >
One benefit to this is that functions which take pointers as arguments can
be annotated with the "nonnull" attribute - < code > __attribute__((nonnull))< / code > in
< a href = "https://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Function-Attributes.html" > GCC< / a > .
The optimizer can sometimes make better decisions knowing that pointer arguments
cannot be null.
< / p >
2018-06-10 04:42:14 +01:00
{#header_open|Optional Type#}
2018-09-14 15:35:03 +01:00
< p > An optional is created by putting {#syntax#}?{#endsyntax#} in front of a type. You can use compile-time
2018-06-10 04:42:14 +01:00
reflection to access the child type of an optional:< / p >
2018-01-31 16:47:56 +00:00
{#code_begin|test#}
const assert = @import("std").debug.assert;
2018-06-10 04:42:14 +01:00
test "optional type" {
2019-11-08 20:56:21 +00:00
// Declare an optional and coerce from null:
2018-01-31 16:47:56 +00:00
var foo: ?i32 = null;
2019-11-08 20:56:21 +00:00
// Coerce from child type of an optional
2018-01-31 16:47:56 +00:00
foo = 1234;
2018-06-10 04:42:14 +01:00
// Use compile-time reflection to access the child type of the optional:
2020-09-04 20:49:14 +01:00
comptime assert(@typeInfo(@TypeOf(foo)).Optional.child == i32);
2018-01-31 16:47:56 +00:00
}
2018-06-14 23:12:05 +01:00
{#code_end#}
{#header_close#}
{#header_open|null#}
< p >
2018-09-14 15:35:03 +01:00
Just like {#link|undefined#}, {#syntax#}null{#endsyntax#} has its own type, and the only way to use it is to
2018-06-14 23:12:05 +01:00
cast it to a different type:
< / p >
{#code_begin|syntax#}
2019-02-22 15:56:49 +00:00
const optional_value: ?i32 = null;
2018-10-05 03:51:36 +01:00
{#code_end#}
{#header_close#}
{#header_open|Optional Pointers#}
< p > An optional pointer is guaranteed to be the same size as a pointer. The {#syntax#}null{#endsyntax#} of
the optional is guaranteed to be address 0.< / p >
{#code_begin|test#}
const assert = @import("std").debug.assert;
test "optional pointers" {
// Pointers cannot be null. If you want a null pointer, use the optional
// prefix `?` to make the pointer type optional.
var ptr: ?*i32 = null;
var x: i32 = 1;
ptr = &x;
assert(ptr.?.* == 1);
// Optional pointers are the same size as normal pointers, because pointer
// value 0 is used as the null value.
assert(@sizeOf(?*i32) == @sizeOf(*i32));
}
2018-01-31 16:47:56 +00:00
{#code_end#}
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Casting#}
2018-06-21 19:43:55 +01:00
< p >
A < strong > type cast< / strong > converts a value of one type to another.
2019-11-08 20:56:21 +00:00
Zig has {#link|Type Coercion#} for conversions that are known to be completely safe and unambiguous,
2018-06-21 19:43:55 +01:00
and {#link|Explicit Casts#} for conversions that one would not want to happen on accident.
There is also a third kind of type conversion called {#link|Peer Type Resolution#} for
the case when a result type must be decided given multiple operand types.
< / p >
2019-11-08 20:56:21 +00:00
{#header_open|Type Coercion#}
2018-06-21 19:43:55 +01:00
< p >
2019-11-08 20:56:21 +00:00
Type coercion occurs when one type is expected, but different type is provided:
2018-06-21 19:43:55 +01:00
< / p >
{#code_begin|test#}
2019-11-08 20:56:21 +00:00
test "type coercion - variable declaration" {
2018-06-21 19:43:55 +01:00
var a: u8 = 1;
var b: u16 = a;
}
2019-11-08 20:56:21 +00:00
test "type coercion - function call" {
2018-06-21 19:43:55 +01:00
var a: u8 = 1;
foo(a);
}
fn foo(b: u16) void {}
2019-11-08 20:56:21 +00:00
test "type coercion - @as builtin" {
2018-06-21 19:43:55 +01:00
var a: u8 = 1;
2019-11-08 20:56:21 +00:00
var b = @as(u16, a);
2018-06-21 19:43:55 +01:00
}
{#code_end#}
2018-06-26 20:48:42 +01:00
< p >
2019-11-08 20:56:21 +00:00
Type coercions are only allowed when it is completely unambiguous how to get from one type to another,
2019-02-14 23:59:20 +00:00
and the transformation is guaranteed to be safe. There is one exception, which is {#link|C Pointers#}.
2018-06-26 20:48:42 +01:00
< / p >
2019-11-08 20:56:21 +00:00
{#header_open|Type Coercion: Stricter Qualification#}
2018-06-21 19:43:55 +01:00
< p >
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:
< / p >
< ul >
2018-09-14 15:35:03 +01:00
< li > {#syntax#}const{#endsyntax#} - non-const to const is allowed< / li >
< li > {#syntax#}volatile{#endsyntax#} - non-volatile to volatile is allowed< / li >
< li > {#syntax#}align{#endsyntax#} - bigger to smaller alignment is allowed < / li >
2018-06-21 19:43:55 +01:00
< li > {#link|error sets|Error Set Type#} to supersets is allowed< / li >
< / ul >
< p >
These casts are no-ops at runtime since the value representation does not change.
< / p >
{#code_begin|test#}
2019-11-08 20:56:21 +00:00
test "type coercion - const qualification" {
2018-06-21 19:43:55 +01:00
var a: i32 = 1;
var b: *i32 = &a;
foo(b);
}
fn foo(a: *const i32) void {}
{#code_end#}
< p >
2019-11-08 20:56:21 +00:00
In addition, pointers coerce to const optional pointers:
2018-06-21 19:43:55 +01:00
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
const mem = std.mem;
test "cast *[1][*]const u8 to [*]const ?[*]const u8" {
2019-11-24 07:14:21 +00:00
const window_name = [1][*]const u8{"window name"};
2018-06-21 19:43:55 +01:00
const x: [*]const ?[*]const u8 = &window_name;
2020-03-30 19:23:22 +01:00
assert(mem.eql(u8, std.mem.spanZ(@ptrCast([*:0]const u8, x[0].?)), "window name"));
2018-06-21 19:43:55 +01:00
}
{#code_end#}
{#header_close#}
2019-11-08 20:56:21 +00:00
{#header_open|Type Coercion: Integer and Float Widening#}
2018-06-21 19:43:55 +01:00
< p >
2019-11-08 20:56:21 +00:00
{#link|Integers#} coerce to integer types which can represent every value of the old type, and likewise
{#link|Floats#} coerce to float types which can represent every value of the old type.
2018-06-21 19:43:55 +01:00
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
const mem = std.mem;
test "integer widening" {
var a: u8 = 250;
var b: u16 = a;
var c: u32 = b;
var d: u64 = c;
var e: u64 = d;
var f: u128 = e;
assert(f == a);
}
test "implicit unsigned integer to signed integer" {
var a: u8 = 250;
var b: i16 = a;
assert(b == 250);
}
test "float widening" {
2020-03-26 23:42:28 +00:00
// Note: there is an open issue preventing this from working on aarch64:
// https://github.com/ziglang/zig/issues/3282
if (std.Target.current.cpu.arch == .aarch64) return error.SkipZigTest;
2018-06-27 17:59:12 +01:00
var a: f16 = 12.34;
var b: f32 = a;
var c: f64 = b;
var d: f128 = c;
assert(d == a);
2020-06-29 01:42:37 +01:00
}
{#code_end#}
{#header_close#}
{#header_open|Type Coercion: Coercion Float to Int#}
< p >
A compiler error is appropriate because this ambiguous expression leaves the compiler
two choices about the coercion.
2020-08-14 17:33:45 +01:00
< / p >
2020-06-29 01:42:37 +01:00
< ul >
< li > Cast {#syntax#}54.0{#endsyntax#} to {#syntax#}comptime_int{#endsyntax#} resulting in {#syntax#}@as(comptime_int, 10){#endsyntax#}, which is casted to {#syntax#}@as(f32, 10){#endsyntax#}< / li >
< li > Cast {#syntax#}5{#endsyntax#} to {#syntax#}comptime_float{#endsyntax#} resulting in {#syntax#}@as(comptime_float, 10.8){#endsyntax#}, which is casted to {#syntax#}@as(f32, 10.8){#endsyntax#}< / li >
< / ul >
{#code_begin|test_err#}
// Compile time coercion of float to int
test "implicit cast to comptime_int" {
var f: f32 = 54.0 / 5;
2018-06-21 19:43:55 +01:00
}
{#code_end#}
{#header_close#}
2019-11-08 20:56:21 +00:00
{#header_open|Type Coercion: Arrays and Pointers#}
2019-11-24 07:14:21 +00:00
{#code_begin|test|coerce_arrays_and_ptrs#}
2019-03-11 23:34:58 +00:00
const std = @import("std");
const assert = std.debug.assert;
// This cast exists primarily so that string literals can be
// passed to functions that accept const slices. However
// it is probably going to be removed from the language when
// https://github.com/ziglang/zig/issues/265 is implemented.
test "[N]T to []const T" {
var x1: []const u8 = "hello";
2019-12-02 02:27:55 +00:00
var x2: []const u8 = & [5]u8{ 'h', 'e', 'l', 'l', 111 };
2019-03-11 23:34:58 +00:00
assert(std.mem.eql(u8, x1, x2));
2019-12-02 02:27:55 +00:00
var y: []const f32 = & [2]f32{ 1.2, 3.4 };
2019-03-11 23:34:58 +00:00
assert(y[0] == 1.2);
}
// Likewise, it works when the destination type is an error union.
test "[N]T to E![]const T" {
var x1: anyerror![]const u8 = "hello";
2019-12-02 02:27:55 +00:00
var x2: anyerror![]const u8 = & [5]u8{ 'h', 'e', 'l', 'l', 111 };
2019-03-11 23:34:58 +00:00
assert(std.mem.eql(u8, try x1, try x2));
2019-12-02 02:27:55 +00:00
var y: anyerror![]const f32 = & [2]f32{ 1.2, 3.4 };
2019-03-11 23:34:58 +00:00
assert((try y)[0] == 1.2);
}
// Likewise, it works when the destination type is an optional.
test "[N]T to ?[]const T" {
var x1: ?[]const u8 = "hello";
2019-12-02 02:27:55 +00:00
var x2: ?[]const u8 = & [5]u8{ 'h', 'e', 'l', 'l', 111 };
2019-03-11 23:34:58 +00:00
assert(std.mem.eql(u8, x1.?, x2.?));
2019-12-02 02:27:55 +00:00
var y: ?[]const f32 = & [2]f32{ 1.2, 3.4 };
2019-03-11 23:34:58 +00:00
assert(y.?[0] == 1.2);
}
// In this cast, the array length becomes the slice length.
test "*[N]T to []T" {
2019-11-24 07:14:21 +00:00
var buf: [5]u8 = "hello".*;
2019-03-11 23:34:58 +00:00
const x: []u8 = &buf;
assert(std.mem.eql(u8, x, "hello"));
const buf2 = [2]f32{ 1.2, 3.4 };
const x2: []const f32 = &buf2;
2019-12-02 02:27:55 +00:00
assert(std.mem.eql(f32, x2, & [2]f32{ 1.2, 3.4 }));
2019-03-11 23:34:58 +00:00
}
2019-11-08 20:56:21 +00:00
// Single-item pointers to arrays can be coerced to
2019-03-11 23:34:58 +00:00
// unknown length pointers.
test "*[N]T to [*]T" {
2019-11-24 07:14:21 +00:00
var buf: [5]u8 = "hello".*;
2019-03-11 23:34:58 +00:00
const x: [*]u8 = &buf;
assert(x[4] == 'o');
// x[5] would be an uncaught out of bounds pointer dereference!
}
// Likewise, it works when the destination type is an optional.
test "*[N]T to ?[*]T" {
2019-11-24 07:14:21 +00:00
var buf: [5]u8 = "hello".*;
2019-03-11 23:34:58 +00:00
const x: ?[*]u8 = &buf;
assert(x.?[4] == 'o');
}
// Single-item pointers can be cast to len-1 single-item arrays.
test "*T to *[1]T" {
var x: i32 = 1234;
const y: *[1]i32 = &x;
const z: [*]i32 = y;
assert(z[0] == 1234);
}
{#code_end#}
{#see_also|C Pointers#}
2018-06-21 19:43:55 +01:00
{#header_close#}
2019-11-08 20:56:21 +00:00
{#header_open|Type Coercion: Optionals#}
2019-03-11 23:34:58 +00:00
< p >
2019-11-08 20:56:21 +00:00
The payload type of {#link|Optionals#}, as well as {#link|null#}, coerce to the optional type.
2019-03-11 23:34:58 +00:00
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
2019-11-08 20:56:21 +00:00
test "coerce to optionals" {
2019-03-11 23:34:58 +00:00
const x: ?i32 = 1234;
const y: ?i32 = null;
assert(x.? == 1234);
assert(y == null);
}
{#code_end#}
< p > It works nested inside the {#link|Error Union Type#}, too:< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
2019-11-08 20:56:21 +00:00
test "coerce to optionals wrapped in error union" {
2019-03-11 23:34:58 +00:00
const x: anyerror!?i32 = 1234;
const y: anyerror!?i32 = null;
assert((try x).? == 1234);
assert((try y) == null);
}
{#code_end#}
2018-06-21 19:43:55 +01:00
{#header_close#}
2019-11-08 20:56:21 +00:00
{#header_open|Type Coercion: Error Unions#}
2019-06-09 04:49:50 +01:00
< p > The payload type of an {#link|Error Union Type#} as well as the {#link|Error Set Type#}
2019-11-08 20:56:21 +00:00
coerce to the error union type:
2019-03-11 23:34:58 +00:00
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
2019-11-08 20:56:21 +00:00
test "coercion to error unions" {
2019-03-11 23:34:58 +00:00
const x: anyerror!i32 = 1234;
const y: anyerror!i32 = error.Failure;
assert((try x) == 1234);
std.testing.expectError(error.Failure, y);
}
{#code_end#}
2018-06-21 19:43:55 +01:00
{#header_close#}
2019-11-08 20:56:21 +00:00
{#header_open|Type Coercion: Compile-Time Known Numbers#}
2019-03-11 23:34:58 +00:00
< p > When a number is {#link|comptime#}-known to be representable in the destination type,
2019-11-08 20:56:21 +00:00
it may be coerced:
2019-03-11 23:34:58 +00:00
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
2019-11-08 20:56:21 +00:00
test "coercing large integer type to smaller one when value is comptime known to fit" {
2019-03-11 23:34:58 +00:00
const x: u64 = 255;
const y: u8 = x;
assert(y == 255);
}
{#code_end#}
2018-06-21 19:43:55 +01:00
{#header_close#}
2019-11-08 20:56:21 +00:00
{#header_open|Type Coercion: unions and enums#}
< p > Tagged unions can be coerced to enums, and enums can be coerced to tagged unions
2019-03-11 23:34:58 +00:00
when they are {#link|comptime#}-known to be a field of the union that has only one possible value, such as
{#link|void#}:
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
const E = enum {
2020-10-14 16:34:05 +01:00
one,
two,
three,
2019-03-11 23:34:58 +00:00
};
const U = union(E) {
2020-10-14 16:34:05 +01:00
one: i32,
two: f32,
three,
2019-03-11 23:34:58 +00:00
};
2019-11-08 20:56:21 +00:00
test "coercion between unions and enums" {
2020-10-14 16:34:05 +01:00
var u = U{ .two = 12.34 };
2019-03-11 23:34:58 +00:00
var e: E = u;
2020-10-14 16:34:05 +01:00
assert(e == E.two);
2019-03-11 23:34:58 +00:00
2020-10-14 16:34:05 +01:00
const three = E.three;
2019-03-11 23:34:58 +00:00
var another_u: U = three;
2020-10-14 16:34:05 +01:00
assert(another_u == E.three);
2019-03-11 23:34:58 +00:00
}
{#code_end#}
{#see_also|union|enum#}
2018-06-21 19:43:55 +01:00
{#header_close#}
2019-11-08 20:56:21 +00:00
{#header_open|Type Coercion: Zero Bit Types#}
< p > {#link|Zero Bit Types#} may be coerced to single-item {#link|Pointers#},
2019-03-11 23:34:58 +00:00
regardless of const.< / p >
< p > TODO document the reasoning for this< / p >
< p > TODO document whether vice versa should work and why< / p >
{#code_begin|test#}
2019-11-08 20:56:21 +00:00
test "coercion of zero bit types" {
2019-03-11 23:34:58 +00:00
var x: void = {};
var y: *void = x;
//var z: void = y; // TODO
}
{#code_end#}
2018-06-21 19:43:55 +01:00
{#header_close#}
2019-11-08 20:56:21 +00:00
{#header_open|Type Coercion: undefined#}
2019-03-11 23:34:58 +00:00
< p > {#link|undefined#} can be cast to any type.< / p >
2018-06-21 19:43:55 +01:00
{#header_close#}
{#header_close#}
{#header_open|Explicit Casts#}
2018-06-26 20:48:42 +01:00
< p >
Explicit casts are performed via {#link|Builtin Functions#}.
Some explicit casts are safe; some are not.
Some explicit casts perform language-level assertions; some do not.
Some explicit casts are no-ops at runtime; some are not.
< / p >
< ul >
< li > {#link|@bitCast#} - change type but maintain bit representation< / li >
< li > {#link|@alignCast#} - make a pointer have more alignment< / li >
< li > {#link|@boolToInt#} - convert true to 1 and false to 0< / li >
< li > {#link|@enumToInt#} - obtain the integer tag value of an enum or tagged union< / li >
< li > {#link|@errSetCast#} - convert to a smaller error set< / li >
< li > {#link|@errorToInt#} - obtain the integer value of an error code< / li >
< li > {#link|@floatCast#} - convert a larger float to a smaller float< / li >
< li > {#link|@floatToInt#} - obtain the integer part of a float value< / li >
< li > {#link|@intCast#} - convert between integer types< / li >
< li > {#link|@intToEnum#} - obtain an enum value based on its integer tag value< / li >
< li > {#link|@intToError#} - obtain an error code based on its integer value< / li >
< li > {#link|@intToFloat#} - convert an integer to a float value< / li >
< li > {#link|@intToPtr#} - convert an address to a pointer< / li >
< li > {#link|@ptrCast#} - convert between pointer types< / li >
< li > {#link|@ptrToInt#} - obtain the address of a pointer< / li >
< li > {#link|@truncate#} - convert between integer types, chopping off bits< / li >
< / ul >
2018-06-21 19:43:55 +01:00
{#header_close#}
{#header_open|Peer Type Resolution#}
2018-08-20 19:21:58 +01:00
< p > Peer Type Resolution occurs in these places:< / p >
< ul >
< li > {#link|switch#} expressions< / li >
< li > {#link|if#} expressions< / li >
< li > {#link|while#} expressions< / li >
< li > {#link|for#} expressions< / li >
< li > Multiple break statements in a block< / li >
< li > Some {#link|binary operations|Table of Operators#}< / li >
< / ul >
< p >
2019-11-08 20:56:21 +00:00
This kind of type resolution chooses a type that all peer types can coerce into. Here are
2018-08-20 19:21:58 +01:00
some examples:
< / p >
2019-11-24 07:14:21 +00:00
{#code_begin|test|peer_type_resolution#}
2018-08-20 19:21:58 +01:00
const std = @import("std");
const assert = std.debug.assert;
const mem = std.mem;
test "peer resolve int widening" {
var a: i8 = 12;
var b: i16 = 34;
var c = a + b;
assert(c == 46);
2019-12-09 20:59:42 +00:00
assert(@TypeOf(c) == i16);
2018-08-20 19:21:58 +01:00
}
test "peer resolve arrays of different size to const slice" {
assert(mem.eql(u8, boolToStr(true), "true"));
assert(mem.eql(u8, boolToStr(false), "false"));
comptime assert(mem.eql(u8, boolToStr(true), "true"));
comptime assert(mem.eql(u8, boolToStr(false), "false"));
}
fn boolToStr(b: bool) []const u8 {
return if (b) "true" else "false";
}
test "peer resolve array and const slice" {
testPeerResolveArrayConstSlice(true);
comptime testPeerResolveArrayConstSlice(true);
}
fn testPeerResolveArrayConstSlice(b: bool) void {
2019-11-08 20:56:21 +00:00
const value1 = if (b) "aoeu" else @as([]const u8, "zz");
const value2 = if (b) @as([]const u8, "zz") else "aoeu";
2018-08-20 19:21:58 +01:00
assert(mem.eql(u8, value1, "aoeu"));
assert(mem.eql(u8, value2, "zz"));
}
test "peer type resolution: ?T and T" {
assert(peerTypeTAndOptionalT(true, false).? == 0);
assert(peerTypeTAndOptionalT(false, false).? == 3);
comptime {
assert(peerTypeTAndOptionalT(true, false).? == 0);
assert(peerTypeTAndOptionalT(false, false).? == 3);
}
}
fn peerTypeTAndOptionalT(c: bool, b: bool) ?usize {
if (c) {
2019-11-08 20:56:21 +00:00
return if (b) null else @as(usize, 0);
2018-08-20 19:21:58 +01:00
}
2019-11-08 20:56:21 +00:00
return @as(usize, 3);
2018-08-20 19:21:58 +01:00
}
2019-12-02 02:27:55 +00:00
test "peer type resolution: *[0]u8 and []const u8" {
2018-08-20 19:21:58 +01:00
assert(peerTypeEmptyArrayAndSlice(true, "hi").len == 0);
assert(peerTypeEmptyArrayAndSlice(false, "hi").len == 1);
comptime {
assert(peerTypeEmptyArrayAndSlice(true, "hi").len == 0);
assert(peerTypeEmptyArrayAndSlice(false, "hi").len == 1);
}
}
fn peerTypeEmptyArrayAndSlice(a: bool, slice: []const u8) []const u8 {
if (a) {
2019-12-02 02:27:55 +00:00
return &[_]u8{};
2018-08-20 19:21:58 +01:00
}
return slice[0..1];
}
2019-12-02 02:27:55 +00:00
test "peer type resolution: *[0]u8, []const u8, and anyerror![]u8" {
2018-08-20 19:21:58 +01:00
{
2019-11-24 07:14:21 +00:00
var data = "hi".*;
2018-08-20 19:21:58 +01:00
const slice = data[0..];
assert((try peerTypeEmptyArrayAndSliceAndError(true, slice)).len == 0);
assert((try peerTypeEmptyArrayAndSliceAndError(false, slice)).len == 1);
}
comptime {
2019-11-24 07:14:21 +00:00
var data = "hi".*;
2018-08-20 19:21:58 +01:00
const slice = data[0..];
assert((try peerTypeEmptyArrayAndSliceAndError(true, slice)).len == 0);
assert((try peerTypeEmptyArrayAndSliceAndError(false, slice)).len == 1);
}
}
2018-11-13 13:08:37 +00:00
fn peerTypeEmptyArrayAndSliceAndError(a: bool, slice: []u8) anyerror![]u8 {
2018-08-20 19:21:58 +01:00
if (a) {
2019-12-02 02:27:55 +00:00
return &[_]u8{};
2018-08-20 19:21:58 +01:00
}
return slice[0..1];
}
2019-03-23 22:46:20 +00:00
test "peer type resolution: *const T and ?*T" {
2019-12-15 11:48:35 +00:00
const a = @intToPtr(*const usize, 0x123456780);
const b = @intToPtr(?*usize, 0x123456780);
2019-03-23 22:46:20 +00:00
assert(a == b);
assert(b == a);
}
2018-08-20 19:21:58 +01:00
{#code_end#}
2018-06-21 19:43:55 +01:00
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 17:02:30 +01:00
2019-02-25 23:31:37 +00:00
{#header_open|Zero Bit Types#}
< p > For some types, {#link|@sizeOf#} is 0:< / p >
< ul >
< li > {#link|void#}< / li >
< li > The {#link|Integers#} {#syntax#}u0{#endsyntax#} and {#syntax#}i0{#endsyntax#}.< / li >
< li > {#link|Arrays#} and {#link|Vectors#} with len 0, or with an element type that is a zero bit type.< / li >
< li > An {#link|enum#} with only 1 tag.< / li >
2019-06-18 14:26:07 +01:00
< li > A {#link|struct#} with all fields being zero bit types.< / li >
2019-02-25 23:31:37 +00:00
< li > A {#link|union#} with only 1 field which is a zero bit type.< / li >
< li > {#link|Pointers to Zero Bit Types#} are themselves zero bit types.< / li >
< / ul >
2018-06-18 17:02:30 +01:00
< p >
2019-02-25 23:31:37 +00:00
These types can only ever have one possible value, and thus
require 0 bits to represent. Code that makes use of these types is
2018-06-18 17:02:30 +01:00
not included in the final generated code:
< / p >
{#code_begin|syntax#}
export fn entry() void {
var x: void = {};
var y: void = {};
x = y;
}
{#code_end#}
2019-02-25 23:31:37 +00:00
< p > When this turns into machine code, there is no code generated in the
body of {#syntax#}entry{#endsyntax#}, even in {#link|Debug#} mode. For example, on x86_64:< / p >
2018-06-18 17:02:30 +01:00
< pre > < code > 0000000000000010 < entry> :
10: 55 push %rbp
11: 48 89 e5 mov %rsp,%rbp
14: 5d pop %rbp
15: c3 retq < / code > < / pre >
< p > These assembly instructions do not have any code associated with the void values -
they only perform the function call prologue and epilog.< / p >
2019-02-25 23:31:37 +00:00
{#header_open|void#}
2018-06-18 17:02:30 +01:00
< p >
2018-09-14 15:35:03 +01:00
{#syntax#}void{#endsyntax#} can be useful for instantiating generic types. For example, given a
{#syntax#}Map(Key, Value){#endsyntax#}, one can pass {#syntax#}void{#endsyntax#} for the {#syntax#}Value{#endsyntax#}
type to make it into a {#syntax#}Set{#endsyntax#}:
2018-06-18 17:02:30 +01:00
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
test "turn HashMap into a set with void" {
2020-07-04 23:25:49 +01:00
var map = std.AutoHashMap(i32, void).init(std.testing.allocator);
2018-06-18 17:02:30 +01:00
defer map.deinit();
2020-07-04 23:25:49 +01:00
try map.put(1, {});
try map.put(2, {});
2018-06-18 17:02:30 +01:00
assert(map.contains(2));
assert(!map.contains(3));
_ = map.remove(2);
assert(!map.contains(2));
}
{#code_end#}
2019-06-09 04:49:50 +01:00
< p > Note that this is different from using a dummy value for the hash map value.
2018-09-14 15:35:03 +01:00
By using {#syntax#}void{#endsyntax#} as the type of the value, the hash map entry type has no value field, and
2018-06-18 17:02:30 +01:00
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.
< / p >
< p >
2018-09-14 15:35:03 +01:00
{#syntax#}void{#endsyntax#} is distinct from {#syntax#}c_void{#endsyntax#}, which is defined like this:
2020-09-26 16:05:11 +01:00
{#syntax#}pub const c_void = opaque {};{#endsyntax#}.
2018-09-14 15:35:03 +01:00
{#syntax#}void{#endsyntax#} has a known size of 0 bytes, and {#syntax#}c_void{#endsyntax#} has an unknown, but non-zero, size.
2018-06-18 17:02:30 +01:00
< / p >
< p >
2018-09-14 15:35:03 +01:00
Expressions of type {#syntax#}void{#endsyntax#} are the only ones whose value can be ignored. For example:
2018-06-18 17:02:30 +01:00
< / p >
{#code_begin|test_err|expression value is ignored#}
test "ignoring expression value" {
foo();
}
fn foo() i32 {
return 1234;
}
{#code_end#}
2018-12-10 05:50:12 +00:00
< p > However, if the expression has type {#syntax#}void{#endsyntax#}, there will be no error. Function return values can also be explicitly ignored by assigning them to {#syntax#}_{#endsyntax#}. < / p >
2018-06-18 17:02:30 +01:00
{#code_begin|test#}
2018-12-10 05:50:12 +00:00
test "void is ignored" {
returnsVoid();
}
test "explicitly ignoring expression value" {
_ = foo();
2018-06-18 17:02:30 +01:00
}
2018-12-10 05:50:12 +00:00
fn returnsVoid() void {}
fn foo() i32 {
return 1234;
}
2018-06-18 17:02:30 +01:00
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 17:02:30 +01:00
2019-02-25 23:31:37 +00:00
{#header_open|Pointers to Zero Bit Types#}
< p > Pointers to zero bit types also have zero bits. They always compare equal to each other:< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
test "pointer to empty struct" {
const Empty = struct {};
var a = Empty{};
var b = Empty{};
var ptr_a = &a;
var ptr_b = &b;
comptime assert(ptr_a == ptr_b);
}
{#code_end#}
< p > The type being pointed to can only ever be one value; therefore loads and stores are
never generated. {#link|ptrToInt#} and {#link|intToPtr#} are not allowed:< / p >
{#code_begin|test_err#}
const Empty = struct {};
test "@ptrToInt for pointer to zero bit type" {
var a = Empty{};
_ = @ptrToInt(&a);
}
test "@intToPtr for pointer to zero bit type" {
_ = @intToPtr(*Empty, 0x1);
}
{#code_end#}
{#header_close#}
{#header_close#}
2019-07-03 18:40:40 +01:00
{#header_open|Result Location Semantics#}
< p >
< a href = "https://github.com/ziglang/zig/issues/2809" > TODO add documentation for this< / a >
< / p >
{#header_close#}
2019-09-25 02:23:12 +01:00
{#header_open|usingnamespace#}
< p >
2019-09-26 00:45:09 +01:00
{#syntax#}usingnamespace{#endsyntax#} is a top level declaration that imports all the public declarations of
2019-09-25 02:23:12 +01:00
the operand, which must be a {#link|struct#}, {#link|union#}, or {#link|enum#}, into the current scope:
< / p >
{#code_begin|test|usingnamespace#}
usingnamespace @import("std");
test "using std namespace" {
debug.assert(true);
}
{#code_end#}
< p >
Instead of the above pattern, it is generally recommended to explicitly alias individual declarations.
However, {#syntax#}usingnamespace{#endsyntax#} has an important use case when organizing the public
API of a file or package. For example, one might have < code > c.zig< / code > with all of the
{#link|C imports|Import from C Header File#}:
< / p >
< pre > {#syntax#}
pub usingnamespace @cImport({
@cInclude("epoxy/gl.h");
@cInclude("GLFW/glfw3.h");
@cDefine("STBI_ONLY_PNG", "");
@cDefine("STBI_NO_STDIO", "");
@cInclude("stb_image.h");
});
{#endsyntax#}< / pre >
< p >
The above example demonstrates using {#syntax#}pub{#endsyntax#} to qualify the
{#syntax#}usingnamespace{#endsyntax#} additionally makes the imported declarations
{#syntax#}pub{#endsyntax#}. This can be used to forward declarations, giving precise control
over what declarations a given file exposes.
< / p >
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|comptime#}
2017-11-07 08:22:27 +00:00
< p >
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.
< / p >
2018-01-17 04:19:05 +00:00
{#header_open|Introducing the Compile-Time Concept#}
{#header_open|Compile-Time Parameters#}
2017-11-07 08:22:27 +00:00
< p >
Compile-time parameters is how Zig implements generics. It is compile-time duck typing.
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
2018-01-25 09:10:11 +00:00
fn max(comptime T: type, a: T, b: T) T {
2018-01-19 08:03:20 +00:00
return if (a > b) a else b;
2017-11-07 08:22:27 +00:00
}
2018-01-25 09:10:11 +00:00
fn gimmeTheBiggerFloat(a: f32, b: f32) f32 {
2018-01-19 08:03:20 +00:00
return max(f32, a, b);
2017-11-07 08:22:27 +00:00
}
2018-01-25 09:10:11 +00:00
fn gimmeTheBiggerInteger(a: u64, b: u64) u64 {
2018-01-19 08:03:20 +00:00
return max(u64, a, b);
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
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 < em > compile-time< / em > ,
2018-09-14 15:35:03 +01:00
which is why the parameter {#syntax#}T{#endsyntax#} in the above snippet must be marked with {#syntax#}comptime{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2018-09-14 15:35:03 +01:00
A {#syntax#}comptime{#endsyntax#} parameter means that:
2017-11-07 08:22:27 +00:00
< / p >
< ul >
< li > At the callsite, the value must be known at compile-time, or it is a compile error.< / li >
< li > In the function definition, the value is known at compile-time.< / li >
< / ul >
< p >
For example, if we were to introduce another function to the above snippet:
< / p >
2019-11-12 22:59:24 +00:00
{#code_begin|test_err|values of type 'type' must be comptime known#}
2018-01-25 09:10:11 +00:00
fn max(comptime T: type, a: T, b: T) T {
2018-01-19 08:03:20 +00:00
return if (a > b) a else b;
2017-11-07 08:22:27 +00:00
}
2018-01-19 08:03:20 +00:00
test "try to pass a runtime type" {
foo(false);
}
2018-01-25 09:10:11 +00:00
fn foo(condition: bool) void {
2017-11-07 08:22:27 +00:00
const result = max(
if (condition) f32 else u64,
1234,
5678);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
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.
< / p >
< p >
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 < em > compile-time duck typing< / em > .
< / p >
< p >
For example:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|operator not allowed for type 'bool'#}
2018-01-25 09:10:11 +00:00
fn max(comptime T: type, a: T, b: T) T {
2018-01-19 08:03:20 +00:00
return if (a > b) a else b;
2017-11-07 08:22:27 +00:00
}
2018-01-19 08:03:20 +00:00
test "try to compare bools" {
_ = max(bool, true, false);
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
On the flip side, inside the function definition with the {#syntax#}comptime{#endsyntax#} parameter, the
2017-11-07 08:22:27 +00:00
value is known at compile-time. This means that we actually could make this work for the bool type
if we wanted to:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
2018-01-25 09:10:11 +00:00
fn max(comptime T: type, a: T, b: T) T {
2017-11-07 08:22:27 +00:00
if (T == bool) {
return a or b;
2018-01-19 08:03:20 +00:00
} else if (a > b) {
2017-11-07 08:22:27 +00:00
return a;
} else {
return b;
}
}
2018-01-19 08:03:20 +00:00
test "try to compare bools" {
@import("std").debug.assert(max(bool, false, true) == true);
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
This works because Zig implicitly inlines {#syntax#}if{#endsyntax#} expressions when the condition
2017-11-07 08:22:27 +00:00
is known at compile-time, and the compiler guarantees that it will skip analysis of
the branch not taken.
< / p >
< p >
2018-09-14 15:35:03 +01:00
This means that the actual function generated for {#syntax#}max{#endsyntax#} in this situation looks like
2017-11-07 08:22:27 +00:00
this:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
2018-01-25 09:10:11 +00:00
fn max(a: bool, b: bool) bool {
2017-11-07 08:22:27 +00:00
return a or b;
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
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.
< / p >
< p >
2018-09-14 15:35:03 +01:00
This works the same way for {#syntax#}switch{#endsyntax#} expressions - they are implicitly inlined
2017-11-07 08:22:27 +00:00
when the target expression is compile-time known.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Compile-Time Variables#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
In Zig, the programmer can label variables as {#syntax#}comptime{#endsyntax#}. This guarantees to the compiler
2017-11-07 08:22:27 +00:00
that every load and store of the variable is performed at compile-time. Any violation of this results in a
compile error.
< / p >
< p >
2018-09-14 15:35:03 +01:00
This combined with the fact that we can {#syntax#}inline{#endsyntax#} loops allows us to write
2017-11-07 08:22:27 +00:00
a function which is partially evaluated at compile-time and partially at run-time.
< / p >
< p >
For example:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test|comptime_vars#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
2018-11-13 13:08:37 +00:00
const CmdFn = struct {
2017-11-07 08:22:27 +00:00
name: []const u8,
2018-01-25 09:10:11 +00:00
func: fn(i32) i32,
2017-11-07 08:22:27 +00:00
};
2019-06-10 00:24:24 +01:00
const cmd_fns = [_]CmdFn{
2018-11-13 13:08:37 +00:00
CmdFn {.name = "one", .func = one},
CmdFn {.name = "two", .func = two},
CmdFn {.name = "three", .func = three},
2017-11-07 08:22:27 +00:00
};
2018-01-25 09:10:11 +00:00
fn one(value: i32) i32 { return value + 1; }
fn two(value: i32) i32 { return value + 2; }
fn three(value: i32) i32 { return value + 3; }
2017-11-07 08:22:27 +00:00
2018-01-25 09:10:11 +00:00
fn performFn(comptime prefix_char: u8, start_value: i32) i32 {
2017-11-07 08:22:27 +00:00
var result: i32 = start_value;
comptime var i = 0;
2018-01-19 08:03:20 +00:00
inline while (i < cmd_fns.len ) : ( i + = 1 ) {
2017-11-07 08:22:27 +00:00
if (cmd_fns[i].name[0] == prefix_char) {
result = cmd_fns[i].func(result);
}
}
return result;
}
test "perform fn" {
assert(performFn('t', 1) == 6);
assert(performFn('o', 0) == 1);
assert(performFn('w', 99) == 99);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
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
2018-09-14 15:35:03 +01:00
different code. In this example, the function {#syntax#}performFn{#endsyntax#} is generated three different times,
for the different values of {#syntax#}prefix_char{#endsyntax#} provided:
2017-11-07 08:22:27 +00:00
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
// From the line:
2017-11-07 08:22:27 +00:00
// assert(performFn('t', 1) == 6);
2018-01-25 09:10:11 +00:00
fn performFn(start_value: i32) i32 {
2017-11-07 08:22:27 +00:00
var result: i32 = start_value;
result = two(result);
result = three(result);
return result;
}
2018-01-19 08:03:20 +00:00
{#code_end#}
{#code_begin|syntax#}
2017-11-07 08:22:27 +00:00
// From the line:
// assert(performFn('o', 0) == 1);
2018-01-25 09:10:11 +00:00
fn performFn(start_value: i32) i32 {
2017-11-07 08:22:27 +00:00
var result: i32 = start_value;
result = one(result);
return result;
}
2018-01-19 08:03:20 +00:00
{#code_end#}
{#code_begin|syntax#}
2017-11-07 08:22:27 +00:00
// From the line:
// assert(performFn('w', 99) == 99);
2018-01-25 09:10:11 +00:00
fn performFn(start_value: i32) i32 {
2017-11-07 08:22:27 +00:00
var result: i32 = start_value;
return result;
2018-01-19 08:03:20 +00:00
}
{#code_end#}
< p >
2017-11-07 08:22:27 +00:00
Note that this happens even in a debug build; in a release build these generated functions still
pass through rigorous LLVM optimizations. The important thing to note, however, is not that this
is a way to write more optimized code, but that it is a way to make sure that what < em > should< / em > happen
at compile-time, < em > does< / em > happen at compile-time. This catches more errors and as demonstrated
later in this article, allows expressiveness that in other languages requires using macros,
generated code, or a preprocessor to accomplish.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Compile-Time Expressions#}
2017-11-07 08:22:27 +00:00
< p >
In Zig, it matters whether a given expression is known at compile-time or run-time. A programmer can
2018-09-14 15:35:03 +01:00
use a {#syntax#}comptime{#endsyntax#} expression to guarantee that the expression will be evaluated at compile-time.
2017-11-07 08:22:27 +00:00
If this cannot be accomplished, the compiler will emit an error. For example:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|unable to evaluate constant expression#}
2018-01-25 09:10:11 +00:00
extern fn exit() noreturn;
2017-11-07 08:22:27 +00:00
2018-01-19 08:03:20 +00:00
test "foo" {
2017-11-07 08:22:27 +00:00
comptime {
exit();
}
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
It doesn't make sense that a program could call {#syntax#}exit(){#endsyntax#} (or any other external function)
at compile-time, so this is a compile error. However, a {#syntax#}comptime{#endsyntax#} expression does much
2017-11-07 08:22:27 +00:00
more than sometimes cause a compile error.
< / p >
< p >
2018-09-14 15:35:03 +01:00
Within a {#syntax#}comptime{#endsyntax#} expression:
2017-11-07 08:22:27 +00:00
< / p >
< ul >
2018-09-14 15:35:03 +01:00
< li > All variables are {#syntax#}comptime{#endsyntax#} variables.< / li >
< li > All {#syntax#}if{#endsyntax#}, {#syntax#}while{#endsyntax#}, {#syntax#}for{#endsyntax#}, and {#syntax#}switch{#endsyntax#}
2017-11-07 08:22:27 +00:00
expressions are evaluated at compile-time, or emit a compile error if this is not possible.< / li >
< li > All function calls cause the compiler to interpret the function at compile-time, emitting a
compile error if the function tries to do something that has global run-time side effects.< / li >
< / ul >
< p >
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.
< / p >
< p >
Let's look at an example:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
2018-01-25 09:10:11 +00:00
fn fibonacci(index: u32) u32 {
2018-01-19 08:03:20 +00:00
if (index < 2 ) return index ;
2017-11-07 08:22:27 +00:00
return fibonacci(index - 1) + fibonacci(index - 2);
}
test "fibonacci" {
// test fibonacci at run-time
assert(fibonacci(7) == 13);
// test fibonacci at compile-time
comptime {
assert(fibonacci(7) == 13);
}
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
Imagine if we had forgotten the base case of the recursive function and tried to run the tests:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|operation caused overflow#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
2018-01-25 09:10:11 +00:00
fn fibonacci(index: u32) u32 {
2018-01-19 08:03:20 +00:00
//if (index < 2 ) return index ;
2017-11-07 08:22:27 +00:00
return fibonacci(index - 1) + fibonacci(index - 2);
}
test "fibonacci" {
comptime {
assert(fibonacci(7) == 13);
}
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
The compiler produces an error which is a stack trace from trying to evaluate the
function at compile-time.
< / p >
< p >
Luckily, we used an unsigned integer, and so when we tried to subtract 1 from 0, it triggered
undefined behavior, which is always a compile error if the compiler knows it happened.
But what would have happened if we used a signed integer?
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|evaluation exceeded 1000 backwards branches#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
2018-01-25 09:10:11 +00:00
fn fibonacci(index: i32) i32 {
2018-01-19 08:03:20 +00:00
//if (index < 2 ) return index ;
2017-11-07 08:22:27 +00:00
return fibonacci(index - 1) + fibonacci(index - 2);
}
test "fibonacci" {
comptime {
assert(fibonacci(7) == 13);
}
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
The compiler noticed that evaluating this function at compile-time took a long time,
and thus emitted a compile error and gave up. If the programmer wants to increase
the budget for compile-time computation, they can use a built-in function called
2018-01-23 04:06:07 +00:00
{#link|@setEvalBranchQuota#} to change the default number 1000 to something else.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2018-09-14 15:35:03 +01:00
What if we fix the base case, but put the wrong value in the {#syntax#}assert{#endsyntax#} line?
2017-11-07 08:22:27 +00:00
< / p >
2019-02-09 00:37:59 +00:00
{#code_begin|test_err|unable to evaluate constant expression#}
2018-01-19 08:03:20 +00:00
const assert = @import("std").debug.assert;
2018-01-25 09:10:11 +00:00
fn fibonacci(index: i32) i32 {
2018-01-19 08:03:20 +00:00
if (index < 2 ) return index ;
return fibonacci(index - 1) + fibonacci(index - 2);
}
test "fibonacci" {
comptime {
2017-11-07 08:22:27 +00:00
assert(fibonacci(7) == 99999);
2018-01-19 08:03:20 +00:00
}
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
What happened is Zig started interpreting the {#syntax#}assert{#endsyntax#} function with the
parameter {#syntax#}ok{#endsyntax#} set to {#syntax#}false{#endsyntax#}. When the interpreter hit
{#syntax#}unreachable{#endsyntax#} it emitted a compile error, because reaching unreachable
2017-11-07 08:22:27 +00:00
code is undefined behavior, and undefined behavior causes a compile error if it is detected
at compile-time.
< / p >
< p >
In the global scope (outside of any function), all expressions are implicitly
2018-09-14 15:35:03 +01:00
{#syntax#}comptime{#endsyntax#} expressions. This means that we can use functions to
2017-11-07 08:22:27 +00:00
initialize complex static data. For example:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
const first_25_primes = firstNPrimes(25);
2019-12-02 02:27:55 +00:00
const sum_of_first_25_primes = sum(&first_25_primes);
2017-11-07 08:22:27 +00:00
2018-01-25 09:10:11 +00:00
fn firstNPrimes(comptime n: usize) [n]i32 {
2017-11-07 08:22:27 +00:00
var prime_list: [n]i32 = undefined;
var next_index: usize = 0;
var test_number: i32 = 2;
2018-01-19 08:03:20 +00:00
while (next_index < prime_list.len ) : ( test_number + = 1 ) {
2017-11-07 08:22:27 +00:00
var test_prime_index: usize = 0;
var is_prime = true;
2018-01-19 08:03:20 +00:00
while (test_prime_index < next_index ) : ( test_prime_index + = 1 ) {
2017-11-07 08:22:27 +00:00
if (test_number % prime_list[test_prime_index] == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
prime_list[next_index] = test_number;
next_index += 1;
}
}
return prime_list;
}
2018-01-25 09:10:11 +00:00
fn sum(numbers: []const i32) i32 {
2017-11-07 08:22:27 +00:00
var result: i32 = 0;
for (numbers) |x| {
result += x;
}
return result;
2018-01-19 08:03:20 +00:00
}
test "variable values" {
@import("std").debug.assert(sum_of_first_25_primes == 1060);
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
When we compile this program, Zig generates the constants
with the answer pre-computed. Here are the lines from the generated LLVM IR:
< / p >
2018-01-19 08:03:20 +00:00
< pre > < code class = "llvm" > @0 = internal unnamed_addr constant [25 x i32] [i32 2, i32 3, i32 5, i32 7, i32 11, i32 13, i32 17, i32 19, i32 23, i32 29, i32 31, i32 37, i32 41, i32 43, i32 47, i32 53, i32 59, i32 61, i32 67, i32 71, i32 73, i32 79, i32 83, i32 89, i32 97]
@1 = internal unnamed_addr constant i32 1060< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
Note that we did not have to do anything special with the syntax of these functions. For example,
2018-09-14 15:35:03 +01:00
we could call the {#syntax#}sum{#endsyntax#} function as is with a slice of numbers whose length and values were
2017-11-07 08:22:27 +00:00
only known at run-time.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_close#}
{#header_open|Generic Data Structures#}
2017-11-07 08:22:27 +00:00
< p >
Zig uses these capabilities to implement generic data structures without introducing any
special-case syntax. If you followed along so far, you may already know how to create a
generic data structure.
< / p >
< p >
2018-09-14 15:35:03 +01:00
Here is an example of a generic {#syntax#}List{#endsyntax#} data structure, that we will instantiate with
the type {#syntax#}i32{#endsyntax#}. In Zig we refer to the type as {#syntax#}List(i32){#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
2018-01-25 09:10:11 +00:00
fn List(comptime T: type) type {
2018-11-13 13:08:37 +00:00
return struct {
2017-11-07 08:22:27 +00:00
items: []T,
len: usize,
2018-01-19 08:03:20 +00:00
};
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
That's it. It's a function that returns an anonymous {#syntax#}struct{#endsyntax#}. For the purposes of error messages
and debugging, Zig infers the name {#syntax#}"List(i32)"{#endsyntax#} from the function name and parameters invoked when creating
2017-11-07 08:22:27 +00:00
the anonymous struct.
< / p >
< p >
To keep the language small and uniform, all aggregate types in Zig are anonymous. To give a type
a name, we assign it to a constant:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
2018-11-13 13:08:37 +00:00
const Node = struct {
2018-05-31 15:56:59 +01:00
next: *Node,
2017-11-07 08:22:27 +00:00
name: []u8,
2018-01-19 08:03:20 +00:00
};
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
This works because all top level declarations are order-independent, and as long as there isn't
an actual infinite regression, values can refer to themselves, directly or indirectly. In this case,
2018-09-14 15:35:03 +01:00
{#syntax#}Node{#endsyntax#} refers to itself as a pointer, which is not actually an infinite regression, so
2017-11-07 08:22:27 +00:00
it works fine.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Case Study: printf in Zig#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
Putting all of this together, let's see how {#syntax#}printf{#endsyntax#} works in Zig.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 08:24:03 +00:00
{#code_begin|exe|printf#}
2020-06-19 10:38:22 +01:00
const print = @import("std").debug.print;
2017-11-07 08:22:27 +00:00
const a_number: i32 = 1234;
const a_string = "foobar";
2018-01-25 09:10:11 +00:00
pub fn main() void {
2020-06-19 10:38:22 +01:00
print("here is a string: '{}' here is a number: {}\n", .{a_string, a_number});
2018-01-17 08:24:03 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
Let's crack open the implementation of this and see how it works:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
/// Calls print and then flushes the buffer.
2020-07-11 12:08:20 +01:00
pub fn printf(self: *OutStream, comptime format: []const u8, args: anytype) anyerror!void {
2018-11-13 13:08:37 +00:00
const State = enum {
2020-10-14 16:34:05 +01:00
start,
open_brace,
close_brace,
2017-11-07 08:22:27 +00:00
};
comptime var start_index: usize = 0;
2020-10-14 16:34:05 +01:00
comptime var state = State.start;
2017-11-07 08:22:27 +00:00
comptime var next_arg: usize = 0;
inline for (format) |c, i| {
switch (state) {
2020-10-14 16:34:05 +01:00
State.start => switch (c) {
2018-01-19 08:03:20 +00:00
'{' => {
if (start_index < i ) try self . write ( format [ start_index . . i ] ) ;
2020-10-14 16:34:05 +01:00
state = State.open_brace;
2017-11-07 08:22:27 +00:00
},
2018-01-19 08:03:20 +00:00
'}' => {
if (start_index < i ) try self . write ( format [ start_index . . i ] ) ;
2020-10-14 16:34:05 +01:00
state = State.close_brace;
2017-11-07 08:22:27 +00:00
},
2018-01-19 08:03:20 +00:00
else => {},
2017-11-07 08:22:27 +00:00
},
2020-10-14 16:34:05 +01:00
State.open_brace => switch (c) {
2018-01-19 08:03:20 +00:00
'{' => {
2020-10-14 16:34:05 +01:00
state = State.start;
2017-11-07 08:22:27 +00:00
start_index = i;
},
2018-01-19 08:03:20 +00:00
'}' => {
2018-01-07 21:51:46 +00:00
try self.printValue(args[next_arg]);
2017-11-07 08:22:27 +00:00
next_arg += 1;
2020-10-14 16:34:05 +01:00
state = State.start;
2017-11-07 08:22:27 +00:00
start_index = i + 1;
},
2018-01-19 08:03:20 +00:00
else => @compileError("Unknown format character: " ++ c),
2017-11-07 08:22:27 +00:00
},
2020-10-14 16:34:05 +01:00
State.close_brace => switch (c) {
2018-01-19 08:03:20 +00:00
'}' => {
2020-10-14 16:34:05 +01:00
state = State.start;
2017-11-07 08:22:27 +00:00
start_index = i;
},
2018-01-19 08:03:20 +00:00
else => @compileError("Single '}' encountered in format string"),
2017-11-07 08:22:27 +00:00
},
}
}
comptime {
if (args.len != next_arg) {
@compileError("Unused arguments");
}
if (state != State.Start) {
@compileError("Incomplete format string: " ++ format);
}
}
2018-01-19 08:03:20 +00:00
if (start_index < format.len ) {
try self.write(format[start_index..format.len]);
2017-11-07 08:22:27 +00:00
}
2018-01-07 21:51:46 +00:00
try self.flush();
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
This is a proof of concept implementation; the actual function in the standard library has more
formatting capabilities.
< / p >
< p >
Note that this is not hard-coded into the Zig compiler; this is userland code in the standard library.
< / p >
< p >
When this function is analyzed from our example code above, Zig partially evaluates the function
and emits a function that actually looks like this:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
2018-05-31 15:56:59 +01:00
pub fn printf(self: *OutStream, arg0: i32, arg1: []const u8) !void {
2018-01-07 21:51:46 +00:00
try self.write("here is a string: '");
try self.printValue(arg0);
try self.write("' here is a number: ");
try self.printValue(arg1);
try self.write("\n");
try self.flush();
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
{#syntax#}printValue{#endsyntax#} is a function that takes a parameter of any type, and does different things depending
2017-11-07 08:22:27 +00:00
on the type:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
2020-07-11 12:08:20 +01:00
pub fn printValue(self: *OutStream, value: anytype) !void {
2020-03-04 03:14:29 +00:00
switch (@typeInfo(@TypeOf(value))) {
.Int => {
return self.printInt(T, value);
},
.Float => {
return self.printFloat(T, value);
},
else => {
@compileError("Unable to print type '" ++ @typeName(T) ++ "'");
},
2017-11-07 08:22:27 +00:00
}
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
And now, what happens if we give too many arguments to {#syntax#}printf{#endsyntax#}?
2017-11-07 08:22:27 +00:00
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|Unused arguments#}
2020-06-19 10:38:22 +01:00
const print = @import("std").debug.print;
2018-01-19 08:03:20 +00:00
const a_number: i32 = 1234;
const a_string = "foobar";
test "printf too many arguments" {
2020-06-19 10:38:22 +01:00
print("here is a string: '{}' here is a number: {}\n", .{
2019-12-09 04:46:50 +00:00
a_string,
a_number,
a_number,
});
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
Zig gives programmers the tools needed to protect themselves against their own mistakes.
< / p >
< p >
Zig doesn't care whether the format argument is a string literal,
2019-11-08 20:56:21 +00:00
only that it is a compile-time known value that can be coerced to a {#syntax#}[]const u8{#endsyntax#}:
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 08:24:03 +00:00
{#code_begin|exe|printf#}
2020-06-19 10:38:22 +01:00
const print = @import("std").debug.print;
2017-11-07 08:22:27 +00:00
const a_number: i32 = 1234;
const a_string = "foobar";
const fmt = "here is a string: '{}' here is a number: {}\n";
2018-01-25 09:10:11 +00:00
pub fn main() void {
2020-06-19 10:38:22 +01:00
print(fmt, .{a_string, a_number});
2018-01-17 08:24:03 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
This works fine.
< / p >
< p >
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.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-19 22:21:08 +01:00
{#see_also|inline while|inline for#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Assembly#}
2019-03-20 23:00:23 +00:00
< p >
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:
< / p >
{#code_begin|exe#}
{#target_linux_x86_64#}
pub fn main() noreturn {
const msg = "hello world\n";
2019-12-05 21:35:23 +00:00
_ = syscall3(SYS_write, STDOUT_FILENO, @ptrToInt(msg), msg.len);
2019-03-20 23:00:23 +00:00
_ = syscall1(SYS_exit, 0);
unreachable;
}
pub const SYS_write = 1;
pub const SYS_exit = 60;
pub const STDOUT_FILENO = 1;
pub fn syscall1(number: usize, arg1: usize) usize {
return asm volatile ("syscall"
: [ret] "={rax}" (-> usize)
: [number] "{rax}" (number),
[arg1] "{rdi}" (arg1)
: "rcx", "r11"
);
}
pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {
return asm volatile ("syscall"
: [ret] "={rax}" (-> usize)
: [number] "{rax}" (number),
[arg1] "{rdi}" (arg1),
[arg2] "{rsi}" (arg2),
[arg3] "{rdx}" (arg3)
: "rcx", "r11"
);
}
{#code_end#}
< p >
Dissecting the syntax:
< / p >
< pre > {#syntax#}// Inline assembly is an expression which returns a value.
// the `asm` keyword begins the expression.
_ = asm
// `volatile` is an optional modifier that tells Zig this
// inline assembly expression has side-effects. Without
// `volatile`, Zig is allowed to delete the inline assembly
// code if the result is unused.
volatile (
// Next is a comptime string which is the assembly code.
// Inside this string one may use `%[ret]`, `%[number]`,
// or `%[arg1]` where a register is expected, to specify
// the register that Zig uses for the argument or return value,
// if the register constraint strings are used. However in
// the below code, this is not used. A literal `%` can be
// obtained by escaping it with a double percent: `%%`.
// Often multiline string syntax comes in handy here.
\\syscall
// Next is the output. It is possible in the future Zig will
// support multiple outputs, depending on how
// https://github.com/ziglang/zig/issues/215 is resolved.
// It is allowed for there to be no outputs, in which case
// this colon would be directly followed by the colon for the inputs.
:
// This specifies the name to be used in `%[ret]` syntax in
// the above assembly string. This example does not use it,
// but the syntax is mandatory.
[ret]
// Next is the output constraint string. This feature is still
// considered unstable in Zig, and so LLVM/GCC documentation
// must be used to understand the semantics.
2019-10-02 07:11:46 +01:00
// http://releases.llvm.org/10.0.0/docs/LangRef.html#inline-asm-constraint-string
2019-03-20 23:00:23 +00:00
// https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html
// In this example, the constraint string means "the result value of
// this inline assembly instruction is whatever is in $rax".
"={rax}"
// Next is either a value binding, or `->` and then a type. The
// type is the result type of the inline assembly expression.
// If it is a value binding, then `%[ret]` syntax would be used
// to refer to the register bound to the value.
(-> usize)
// Next is the list of inputs.
// The constraint for these inputs means, "when the assembly code is
// executed, $rax shall have the value of `number` and $rdi shall have
// the value of `arg1`". Any number of input parameters is allowed,
// including none.
: [number] "{rax}" (number),
[arg1] "{rdi}" (arg1)
// Next is the list of clobbers. These declare a set of registers whose
2019-09-19 16:14:42 +01:00
// values will not be preserved by the execution of this assembly code.
2019-03-20 23:00:23 +00:00
// These do not include output or input registers. The special clobber
// value of "memory" means that the assembly writes to arbitrary undeclared
// memory locations - not only the memory pointed to by a declared indirect
// output. In this example we list $rcx and $r11 because it is known the
// kernel syscall does not preserve these registers.
: "rcx", "r11"
);{#endsyntax#}< / pre >
< p >
For i386 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.
< / p >
< p >
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.
< / p >
{#header_open|Output Constraints#}
< p >
2019-09-19 16:14:42 +01:00
Output constraints are still considered to be unstable in Zig, and
2019-03-20 23:00:23 +00:00
so
2019-10-02 07:11:46 +01:00
< a href = "http://releases.llvm.org/10.0.0/docs/LangRef.html#inline-asm-constraint-string" > LLVM documentation< / a >
2019-03-20 23:00:23 +00:00
and
< a href = "https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html" > GCC documentation< / a >
must be used to understand the semantics.
< / p >
< p >
Note that some breaking changes to output constraints are planned with
< a href = "https://github.com/ziglang/zig/issues/215" > issue #215< / a > .
< / p >
{#header_close#}
{#header_open|Input Constraints#}
< p >
2019-09-19 16:14:42 +01:00
Input constraints are still considered to be unstable in Zig, and
2019-03-20 23:00:23 +00:00
so
2019-10-02 07:11:46 +01:00
< a href = "http://releases.llvm.org/10.0.0/docs/LangRef.html#inline-asm-constraint-string" > LLVM documentation< / a >
2019-03-20 23:00:23 +00:00
and
< a href = "https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html" > GCC documentation< / a >
must be used to understand the semantics.
< / p >
< p >
Note that some breaking changes to input constraints are planned with
< a href = "https://github.com/ziglang/zig/issues/215" > issue #215< / a > .
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2019-03-20 23:00:23 +00:00
{#header_open|Clobbers#}
< p >
Clobbers are the set of registers whose values will not be preserved by the execution of
the assembly code. These do not include output or input registers. The special clobber
value of {#syntax#}"memory"{#endsyntax#} means that the assembly causes writes to
arbitrary undeclared memory locations - not only the memory pointed to by a declared
2019-09-19 16:14:42 +01:00
indirect output.
2019-03-20 23:00:23 +00:00
< / p >
< p >
Failure to declare the full set of clobbers for a given inline assembly
expression is unchecked {#link|Undefined Behavior#}.
< / p >
{#header_close#}
{#header_open|Global Assembly#}
< p >
When an assembly expression occurs in a top level {#link|comptime#} block, this is
< strong > global assembly< / strong > .
< / p >
< p >
This kind of assembly has different rules than inline assembly. First, {#syntax#}volatile{#endsyntax#}
is not valid because all global assembly is unconditionally included.
Second, there are no inputs, outputs, or clobbers. All global assembly is concatenated
verbatim into one long string and assembled together. There are no template substitution rules regarding
< code > %< / code > as there are in inline assembly expressions.
< / p >
{#code_begin|test|global-asm#}
{#target_linux_x86_64#}
const std = @import("std");
const assert = std.debug.assert;
comptime {
asm (
\\.global my_func;
\\.type my_func, @function;
\\my_func:
\\ lea (%rdi,%rsi,1),%eax
\\ retq
);
}
extern fn my_func(a: i32, b: i32) i32;
test "global assembly" {
assert(my_func(12, 34) == 46);
}
{#code_end#}
{#header_close#}
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|Atomics#}
2017-11-07 08:22:27 +00:00
< p > TODO: @fence()< / p >
< p > TODO: @atomic rmw< / p >
< p > TODO: builtin atomic memory ordering enum< / p >
2018-06-11 22:34:45 +01:00
{#header_close#}
2019-08-13 19:14:19 +01:00
{#header_open|Async Functions#}
2018-06-11 22:34:45 +01:00
< p >
2019-08-15 21:46:43 +01:00
When a function is called, a frame is pushed to the stack,
the function runs until it reaches a return statement, and then the frame is popped from the stack.
At the callsite, the following code does not run until the function returns.
2018-06-11 22:34:45 +01:00
< / p >
< p >
2019-08-15 21:46:43 +01:00
An async function is a function whose callsite is split into an {#syntax#}async{#endsyntax#} initiation,
followed by an {#syntax#}await{#endsyntax#} completion. Its frame is
provided explicitly by the caller, and it can be suspended and resumed any number of times.
2018-06-11 22:34:45 +01:00
< / p >
< p >
2019-08-15 21:46:43 +01:00
Zig infers that a function is {#syntax#}async{#endsyntax#} when it observes that the function contains
a < strong > suspension point< / strong > . Async functions can be called the same as normal functions. A
function call of an async function is a suspend point.
2018-06-11 22:34:45 +01:00
< / p >
2019-08-15 21:46:43 +01:00
{#header_open|Suspend and Resume#}
2018-06-11 22:34:45 +01:00
< p >
2019-08-15 21:46:43 +01:00
At any point, a function may suspend itself. This causes control flow to
return to the callsite (in the case of the first suspension),
or resumer (in the case of subsequent suspensions).
2018-06-11 22:34:45 +01:00
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
var x: i32 = 1;
2019-08-15 21:46:43 +01:00
test "suspend with no resume" {
var frame = async func();
2018-06-11 22:34:45 +01:00
assert(x == 2);
}
2019-08-15 21:46:43 +01:00
fn func() void {
2019-08-12 00:53:10 +01:00
x += 1;
2018-06-11 22:34:45 +01:00
suspend;
2019-08-15 21:46:43 +01:00
// This line is never reached because the suspend has no matching resume.
2018-06-11 22:34:45 +01:00
x += 1;
}
{#code_end#}
< p >
2019-08-15 21:46:43 +01:00
In the same way that each allocation should have a corresponding free,
Each {#syntax#}suspend{#endsyntax#} should have a corresponding {#syntax#}resume{#endsyntax#}.
A < strong > suspend block< / strong > allows a function to put a pointer to its own
frame somewhere, for example into an event loop, even if that action will perform a
{#syntax#}resume{#endsyntax#} operation on a different thread.
{#link|@frame#} provides access to the async function frame pointer.
2018-06-11 22:34:45 +01:00
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
2019-08-12 00:53:10 +01:00
var the_frame: anyframe = undefined;
var result = false;
2019-08-13 19:14:19 +01:00
test "async function suspend with block" {
2019-08-12 00:53:10 +01:00
_ = async testSuspendBlock();
2019-08-15 21:46:43 +01:00
assert(!result);
2019-08-12 00:53:10 +01:00
resume the_frame;
2019-08-15 21:46:43 +01:00
assert(result);
2018-06-11 22:34:45 +01:00
}
2019-08-12 00:53:10 +01:00
fn testSuspendBlock() void {
2018-07-29 09:19:36 +01:00
suspend {
2019-12-09 20:59:42 +00:00
comptime assert(@TypeOf(@frame()) == *@Frame(testSuspendBlock));
2019-08-12 00:53:10 +01:00
the_frame = @frame();
2018-06-11 22:34:45 +01:00
}
result = true;
}
{#code_end#}
< p >
2019-08-15 21:46:43 +01:00
{#syntax#}suspend{#endsyntax#} causes a function to be {#syntax#}async{#endsyntax#}.
2018-06-11 22:34:45 +01:00
< / p >
2019-08-15 21:46:43 +01:00
2018-08-20 19:21:58 +01:00
{#header_open|Resuming from Suspend Blocks#}
2018-06-11 22:34:45 +01:00
< p >
2019-08-13 19:14:19 +01:00
Upon entering a {#syntax#}suspend{#endsyntax#} block, the async function is already considered
2018-06-11 22:34:45 +01:00
suspended, and can be resumed. For example, if you started another kernel thread,
2019-08-15 21:46:43 +01:00
and had that thread call {#syntax#}resume{#endsyntax#} on the frame pointer provided by the
{#link|@frame#}, the new thread would begin executing after the suspend
2018-06-11 22:34:45 +01:00
block, while the old thread continued executing the suspend block.
< / p >
< p >
2019-08-13 19:14:19 +01:00
However, the async function can be directly resumed from the suspend block, in which case it
2018-06-11 22:34:45 +01:00
never returns to its resumer and continues executing.
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
2018-07-30 18:07:04 +01:00
test "resume from suspend" {
2018-06-11 22:34:45 +01:00
var my_result: i32 = 1;
2019-08-12 00:53:10 +01:00
_ = async testResumeFromSuspend(&my_result);
2018-06-11 22:34:45 +01:00
std.debug.assert(my_result == 2);
}
2019-08-15 21:46:43 +01:00
fn testResumeFromSuspend(my_result: *i32) void {
2018-08-02 09:45:35 +01:00
suspend {
2019-08-12 00:53:10 +01:00
resume @frame();
2018-06-11 22:34:45 +01:00
}
my_result.* += 1;
suspend;
my_result.* += 1;
}
{#code_end#}
2018-08-20 19:21:58 +01:00
< p >
2019-08-15 21:46:43 +01:00
This is guaranteed to tail call, and therefore will not cause a new stack frame.
2018-08-20 19:21:58 +01:00
< / p >
2018-06-11 22:34:45 +01:00
{#header_close#}
{#header_close#}
2019-08-15 21:46:43 +01:00
{#header_open|Async and Await#}
2018-06-11 22:34:45 +01:00
< p >
2019-08-15 21:46:43 +01:00
In the same way that every {#syntax#}suspend{#endsyntax#} has a matching
{#syntax#}resume{#endsyntax#}, every {#syntax#}async{#endsyntax#} has a matching {#syntax#}await{#endsyntax#}.
2018-06-11 22:34:45 +01:00
< / p >
2019-08-15 21:46:43 +01:00
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
test "async and await" {
// Here we have an exception where we do not match an async
// with an await. The test block is not async and so cannot
// have a suspend point in it.
// This is well-defined behavior, and everything is OK here.
// Note however that there would be no way to collect the
// return value of amain, if it were something other than void.
_ = async amain();
}
fn amain() void {
var frame = async func();
2019-12-09 20:59:42 +00:00
comptime assert(@TypeOf(frame) == @Frame(func));
2019-08-15 21:46:43 +01:00
const ptr: anyframe->void = &frame;
const any_ptr: anyframe = ptr;
resume any_ptr;
await ptr;
}
fn func() void {
suspend;
}
{#code_end#}
2018-06-11 22:34:45 +01:00
< p >
2019-08-15 21:46:43 +01:00
The {#syntax#}await{#endsyntax#} keyword is used to coordinate with an async function's
{#syntax#}return{#endsyntax#} statement.
2018-06-11 22:34:45 +01:00
< / p >
< p >
2019-08-15 21:46:43 +01:00
{#syntax#}await{#endsyntax#} is a suspend point, and takes as an operand anything that
2019-11-08 20:56:21 +00:00
coerces to {#syntax#}anyframe->T{#endsyntax#}.
2018-06-11 22:34:45 +01:00
< / p >
< p >
2019-08-15 21:46:43 +01:00
There is a common misconception that {#syntax#}await{#endsyntax#} resumes the target function.
It is the other way around: it suspends until the target function completes.
In the event that the target function has already completed, {#syntax#}await{#endsyntax#}
does not suspend; instead it copies the
return value directly from the target function's frame.
2018-06-11 22:34:45 +01:00
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
2019-08-12 00:53:10 +01:00
var the_frame: anyframe = undefined;
2018-06-11 22:34:45 +01:00
var final_result: i32 = 0;
2019-08-13 19:14:19 +01:00
test "async function await" {
2018-06-11 22:34:45 +01:00
seq('a');
2019-08-12 00:53:10 +01:00
_ = async amain();
2018-06-11 22:34:45 +01:00
seq('f');
2019-08-12 00:53:10 +01:00
resume the_frame;
2018-06-11 22:34:45 +01:00
seq('i');
assert(final_result == 1234);
2019-12-02 02:27:55 +00:00
assert(std.mem.eql(u8, & seq_points, "abcdefghi"));
2018-06-11 22:34:45 +01:00
}
2019-08-15 21:46:43 +01:00
fn amain() void {
2018-06-11 22:34:45 +01:00
seq('b');
2019-08-12 00:53:10 +01:00
var f = async another();
2018-06-11 22:34:45 +01:00
seq('e');
2019-08-12 00:53:10 +01:00
final_result = await f;
2018-06-11 22:34:45 +01:00
seq('h');
}
2019-08-15 21:46:43 +01:00
fn another() i32 {
2018-06-11 22:34:45 +01:00
seq('c');
2018-07-29 09:19:36 +01:00
suspend {
2018-06-11 22:34:45 +01:00
seq('d');
2019-08-12 00:53:10 +01:00
the_frame = @frame();
2018-06-11 22:34:45 +01:00
}
seq('g');
return 1234;
}
2019-06-10 00:24:24 +01:00
var seq_points = [_]u8{0} ** "abcdefghi".len;
2018-06-11 22:34:45 +01:00
var seq_index: usize = 0;
fn seq(c: u8) void {
seq_points[seq_index] = c;
seq_index += 1;
}
{#code_end#}
< p >
2018-09-14 15:35:03 +01:00
In general, {#syntax#}suspend{#endsyntax#} is lower level than {#syntax#}await{#endsyntax#}. Most application
2019-08-15 21:46:43 +01:00
code will use only {#syntax#}async{#endsyntax#} and {#syntax#}await{#endsyntax#}, but event loop
implementations will make use of {#syntax#}suspend{#endsyntax#} internally.
2018-06-11 22:34:45 +01:00
< / p >
{#header_close#}
2019-08-15 21:46:43 +01:00
{#header_open|Async Function Example#}
2018-06-11 22:34:45 +01:00
< p >
2019-08-15 21:46:43 +01:00
Putting all of this together, here is an example of typical
{#syntax#}async{#endsyntax#}/{#syntax#}await{#endsyntax#} usage:
< / p >
{#code_begin|exe|async#}
const std = @import("std");
const Allocator = std.mem.Allocator;
pub fn main() void {
_ = async amainWrap();
// Typically we would use an event loop to manage resuming async functions,
// but in this example we hard code what the event loop would do,
// to make things deterministic.
resume global_file_frame;
resume global_download_frame;
}
fn amainWrap() void {
amain() catch |e| {
2020-06-19 10:38:22 +01:00
std.debug.print("{}\n", .{e});
2019-08-15 21:46:43 +01:00
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
}
std.process.exit(1);
};
}
fn amain() !void {
2019-11-25 22:25:06 +00:00
const allocator = std.heap.page_allocator;
2019-08-15 21:46:43 +01:00
var download_frame = async fetchUrl(allocator, "https://example.com/");
var awaited_download_frame = false;
errdefer if (!awaited_download_frame) {
if (await download_frame) |r| allocator.free(r) else |_| {}
};
var file_frame = async readFile(allocator, "something.txt");
var awaited_file_frame = false;
errdefer if (!awaited_file_frame) {
if (await file_frame) |r| allocator.free(r) else |_| {}
};
awaited_file_frame = true;
const file_text = try await file_frame;
defer allocator.free(file_text);
awaited_download_frame = true;
const download_text = try await download_frame;
defer allocator.free(download_text);
2020-06-19 10:38:22 +01:00
std.debug.print("download_text: {}\n", .{download_text});
std.debug.print("file_text: {}\n", .{file_text});
2019-08-15 21:46:43 +01:00
}
var global_download_frame: anyframe = undefined;
fn fetchUrl(allocator: *Allocator, url: []const u8) ![]u8 {
const result = try std.mem.dupe(allocator, u8, "this is the downloaded url contents");
errdefer allocator.free(result);
suspend {
global_download_frame = @frame();
}
2020-06-19 10:38:22 +01:00
std.debug.print("fetchUrl returning\n", .{});
2019-08-15 21:46:43 +01:00
return result;
}
var global_file_frame: anyframe = undefined;
fn readFile(allocator: *Allocator, filename: []const u8) ![]u8 {
const result = try std.mem.dupe(allocator, u8, "this is the file contents");
errdefer allocator.free(result);
suspend {
global_file_frame = @frame();
}
2020-06-19 10:38:22 +01:00
std.debug.print("readFile returning\n", .{});
2019-08-15 21:46:43 +01:00
return result;
}
{#code_end#}
< p >
Now we remove the {#syntax#}suspend{#endsyntax#} and {#syntax#}resume{#endsyntax#} code, and
observe the same behavior, with one tiny difference:
< / p >
{#code_begin|exe|blocking#}
const std = @import("std");
const Allocator = std.mem.Allocator;
pub fn main() void {
_ = async amainWrap();
}
fn amainWrap() void {
amain() catch |e| {
2020-06-19 10:38:22 +01:00
std.debug.print("{}\n", .{e});
2019-08-15 21:46:43 +01:00
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
}
std.process.exit(1);
};
}
fn amain() !void {
2019-11-25 22:25:06 +00:00
const allocator = std.heap.page_allocator;
2019-08-15 21:46:43 +01:00
var download_frame = async fetchUrl(allocator, "https://example.com/");
var awaited_download_frame = false;
errdefer if (!awaited_download_frame) {
if (await download_frame) |r| allocator.free(r) else |_| {}
};
var file_frame = async readFile(allocator, "something.txt");
var awaited_file_frame = false;
errdefer if (!awaited_file_frame) {
if (await file_frame) |r| allocator.free(r) else |_| {}
};
awaited_file_frame = true;
const file_text = try await file_frame;
defer allocator.free(file_text);
awaited_download_frame = true;
const download_text = try await download_frame;
defer allocator.free(download_text);
2020-06-19 10:38:22 +01:00
std.debug.print("download_text: {}\n", .{download_text});
std.debug.print("file_text: {}\n", .{file_text});
2019-08-15 21:46:43 +01:00
}
fn fetchUrl(allocator: *Allocator, url: []const u8) ![]u8 {
const result = try std.mem.dupe(allocator, u8, "this is the downloaded url contents");
errdefer allocator.free(result);
2020-06-19 10:38:22 +01:00
std.debug.print("fetchUrl returning\n", .{});
2019-08-15 21:46:43 +01:00
return result;
}
fn readFile(allocator: *Allocator, filename: []const u8) ![]u8 {
const result = try std.mem.dupe(allocator, u8, "this is the file contents");
errdefer allocator.free(result);
2020-06-19 10:38:22 +01:00
std.debug.print("readFile returning\n", .{});
2019-08-15 21:46:43 +01:00
return result;
}
{#code_end#}
< p >
Previously, the {#syntax#}fetchUrl{#endsyntax#} and {#syntax#}readFile{#endsyntax#} functions suspended,
and were resumed in an order determined by the {#syntax#}main{#endsyntax#} function. Now,
since there are no suspend points, the order of the printed "... returning" messages
is determined by the order of {#syntax#}async{#endsyntax#} callsites.
2018-06-11 22:34:45 +01:00
< / p >
{#header_close#}
2019-02-22 15:56:49 +00:00
2018-01-17 04:19:05 +00:00
{#header_close#}
2019-10-23 11:55:20 +01:00
{#header_open|Builtin Functions|2col#}
2017-11-07 08:22:27 +00:00
< p >
Builtin functions are provided by the compiler and are prefixed with < code > @< / code > .
2018-09-14 15:35:03 +01:00
The {#syntax#}comptime{#endsyntax#} keyword on a parameter means that the parameter must be known
2017-11-07 08:22:27 +00:00
at compile time.
< / p >
2018-01-17 04:19:05 +00:00
{#header_open|@addWithOverflow#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@addWithOverflow(comptime T: type, a: T, b: T, result: *T) bool{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
Performs {#syntax#}result.* = a + b{#endsyntax#}. If overflow or underflow occurs,
stores the overflowed bits in {#syntax#}result{#endsyntax#} and returns {#syntax#}true{#endsyntax#}.
If no overflow or underflow occurs, returns {#syntax#}false{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
{#header_open|@alignCast#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@alignCast(comptime alignment: u29, ptr: anytype) anytype{#endsyntax#}< / pre >
2018-12-15 01:21:23 +00:00
< p >
{#syntax#}ptr{#endsyntax#} can be {#syntax#}*T{#endsyntax#}, {#syntax#}fn(){#endsyntax#}, {#syntax#}?*T{#endsyntax#},
{#syntax#}?fn(){#endsyntax#}, or {#syntax#}[]T{#endsyntax#}. It returns the same type as {#syntax#}ptr{#endsyntax#}
except with the alignment adjusted to the new value.
< / p >
< p > A {#link|pointer alignment safety check|Incorrect Pointer Alignment#} is added
to the generated code to make sure the pointer is aligned as promised.< / p >
{#header_close#}
{#header_open|@alignOf#}
< pre > {#syntax#}@alignOf(comptime T: type) comptime_int{#endsyntax#}< / pre >
< p >
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.
< / p >
< pre > {#syntax#}const assert = @import("std").debug.assert;
comptime {
assert(*u32 == *align(@alignOf(u32)) u32);
}{#endsyntax#}< / pre >
< p >
The result is a target-specific compile time constant. It is guaranteed to be
less than or equal to {#link|@sizeOf(T)|@sizeOf#}.
< / p >
{#see_also|Alignment#}
{#header_close#}
2019-08-15 21:46:43 +01:00
2019-11-08 00:05:52 +00:00
{#header_open|@as#}
< pre > {#syntax#}@as(comptime T: type, expression) T{#endsyntax#}< / pre >
< p >
Performs {#link|Type Coercion#}. This cast is allowed when the conversion is unambiguous and safe,
and is the preferred way to convert between types, whenever possible.
< / p >
{#header_close#}
2019-08-15 21:46:43 +01:00
{#header_open|@asyncCall#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@asyncCall(frame_buffer: []align(@alignOf(@Frame(anyAsyncFunction))) u8, result_ptr, function_ptr, args: anytype) anyframe->T{#endsyntax#}< / pre >
2019-08-15 21:46:43 +01:00
< p >
{#syntax#}@asyncCall{#endsyntax#} performs an {#syntax#}async{#endsyntax#} call on a function pointer,
which may or may not be an {#link|async function|Async Functions#}.
< / p >
< p >
The provided {#syntax#}frame_buffer{#endsyntax#} must be large enough to fit the entire function frame.
This size can be determined with {#link|@frameSize#}. To provide a too-small buffer
invokes safety-checked {#link|Undefined Behavior#}.
< / p >
< p >
{#syntax#}result_ptr{#endsyntax#} is optional ({#link|null#} may be provided). If provided,
the function call will write its result directly to the result pointer, which will be available to
read after {#link|await|Async and Await#} completes. Any result location provided to
{#syntax#}await{#endsyntax#} will copy the result from {#syntax#}result_ptr{#endsyntax#}.
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
test "async fn pointer in a struct field" {
var data: i32 = 1;
const Foo = struct {
2020-05-04 17:50:11 +01:00
bar: fn (*i32) callconv(.Async) void,
2019-08-15 21:46:43 +01:00
};
var foo = Foo{ .bar = func };
2019-08-17 17:48:48 +01:00
var bytes: [64]u8 align(@alignOf(@Frame(func))) = undefined;
2020-06-24 17:01:38 +01:00
const f = @asyncCall(& bytes, {}, foo.bar, .{&data});
2019-08-15 21:46:43 +01:00
assert(data == 2);
resume f;
assert(data == 4);
}
2020-05-04 17:50:11 +01:00
fn func(y: *i32) void {
2019-08-15 21:46:43 +01:00
defer y.* += 2;
y.* += 1;
suspend;
}
{#code_end#}
{#header_close#}
2018-04-15 23:12:00 +01:00
{#header_open|@atomicLoad#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@atomicLoad(comptime T: type, ptr: *const T, comptime ordering: builtin.AtomicOrder) T{#endsyntax#}< / pre >
2018-04-15 23:12:00 +01:00
< p >
This builtin function atomically dereferences a pointer and returns the value.
< / p >
< p >
2020-09-04 19:41:34 +01:00
{#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float,
2020-03-11 11:29:17 +00:00
an integer or an enum.
2018-04-15 23:12:00 +01:00
< / p >
{#header_close#}
2018-03-01 02:19:51 +00:00
{#header_open|@atomicRmw#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@atomicRmw(comptime T: type, ptr: *T, comptime op: builtin.AtomicRmwOp, operand: T, comptime ordering: builtin.AtomicOrder) T{#endsyntax#}< / pre >
2018-03-01 02:19:51 +00:00
< p >
This builtin function atomically modifies memory and then returns the previous value.
< / p >
< p >
2020-09-04 19:41:34 +01:00
{#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float,
2020-03-11 11:29:17 +00:00
an integer or an enum.
2018-03-01 02:19:51 +00:00
< / p >
2019-08-02 23:53:56 +01:00
< p >
Supported operations:
< / p >
< ul >
2019-12-16 22:28:17 +00:00
< li > {#syntax#}.Xchg{#endsyntax#} - stores the operand unmodified. Supports enums, integers and floats.< / li >
2019-08-02 23:53:56 +01:00
< li > {#syntax#}.Add{#endsyntax#} - for integers, twos complement wraparound addition.
Also supports {#link|Floats#}.< / li >
< li > {#syntax#}.Sub{#endsyntax#} - for integers, twos complement wraparound subtraction.
Also supports {#link|Floats#}.< / li >
< li > {#syntax#}.And{#endsyntax#} - bitwise and< / li >
< li > {#syntax#}.Nand{#endsyntax#} - bitwise nand< / li >
< li > {#syntax#}.Or{#endsyntax#} - bitwise or< / li >
< li > {#syntax#}.Xor{#endsyntax#} - bitwise xor< / li >
< li > {#syntax#}.Max{#endsyntax#} - stores the operand if it is larger. Supports integers and floats.< / li >
< li > {#syntax#}.Min{#endsyntax#} - stores the operand if it is smaller. Supports integers and floats.< / li >
< / ul >
2018-03-01 02:19:51 +00:00
{#header_close#}
2019-11-12 22:25:44 +00:00
{#header_open|@atomicStore#}
< pre > {#syntax#}@atomicStore(comptime T: type, ptr: *T, value: T, comptime ordering: builtin.AtomicOrder) void{#endsyntax#}< / pre >
< p >
This builtin function atomically stores a value.
< / p >
< p >
2020-09-04 19:41:34 +01:00
{#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float,
2020-03-11 11:29:17 +00:00
an integer or an enum.
2019-11-12 22:25:44 +00:00
< / p >
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@bitCast#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@bitCast(comptime DestType: type, value: anytype) DestType{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
Converts a value of one type to another type.
< / p >
< p >
2019-12-09 20:59:42 +00:00
Asserts that {#syntax#}@sizeOf(@TypeOf(value)) == @sizeOf(DestType){#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2020-02-24 21:21:11 +00:00
Asserts that {#syntax#}@typeInfo(DestType) != .Pointer{#endsyntax#}. Use {#syntax#}@ptrCast{#endsyntax#} or {#syntax#}@intToPtr{#endsyntax#} if you need this.
2017-11-07 08:22:27 +00:00
< / p >
< p >
Can be used for these things for example:
< / p >
< ul >
2018-09-14 15:35:03 +01:00
< li > Convert {#syntax#}f32{#endsyntax#} to {#syntax#}u32{#endsyntax#} bits< / li >
< li > Convert {#syntax#}i32{#endsyntax#} to {#syntax#}u32{#endsyntax#} preserving twos complement< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< p >
2018-09-14 15:35:03 +01:00
Works at compile-time if {#syntax#}value{#endsyntax#} is known at compile time. It's a compile error to bitcast a struct to a scalar type of the same size since structs have undefined layout. However if the struct is packed then it works.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-09-21 19:15:58 +01:00
{#header_open|@bitOffsetOf#}
2019-06-10 00:24:24 +01:00
< pre > {#syntax#}@bitOffsetOf(comptime T: type, comptime field_name: []const u8) comptime_int{#endsyntax#}< / pre >
2018-09-21 19:15:58 +01:00
< p >
Returns the bit offset of a field relative to its containing struct.
< / p >
< p >
For non {#link|packed structs|packed struct#}, this will always be divisible by {#syntax#}8{#endsyntax#}.
For packed structs, non-byte-aligned fields will share a byte offset, but they will have different
bit offsets.
< / p >
{#see_also|@byteOffsetOf#}
{#header_close#}
2018-06-18 08:07:16 +01:00
{#header_open|@boolToInt#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@boolToInt(value: bool) u1{#endsyntax#}< / pre >
2018-06-18 08:07:16 +01:00
< p >
2018-09-14 15:35:03 +01:00
Converts {#syntax#}true{#endsyntax#} to {#syntax#}u1(1){#endsyntax#} and {#syntax#}false{#endsyntax#} to
{#syntax#}u1(0){#endsyntax#}.
2018-06-18 08:07:16 +01:00
< / p >
< p >
2018-09-14 15:35:03 +01:00
If the value is known at compile-time, the return type is {#syntax#}comptime_int{#endsyntax#}
instead of {#syntax#}u1{#endsyntax#}.
2018-06-18 08:07:16 +01:00
< / p >
{#header_close#}
2020-01-16 15:12:43 +00:00
{#header_open|@bitSizeOf#}
< pre > {#syntax#}@bitSizeOf(comptime T: type) comptime_int{#endsyntax#}< / pre >
< p >
This function returns the number of bits it takes to store {#syntax#}T{#endsyntax#} in memory.
The result is a target-specific compile time constant.
< / p >
< p >
This function measures the size at runtime. For types that are disallowed at runtime, such as
{#syntax#}comptime_int{#endsyntax#} and {#syntax#}type{#endsyntax#}, the result is {#syntax#}0{#endsyntax#}.
< / p >
{#see_also|@sizeOf|@typeInfo#}
{#header_close#}
2018-12-15 01:21:23 +00:00
{#header_open|@breakpoint#}
< pre > {#syntax#}@breakpoint(){#endsyntax#}< / pre >
< p >
This function inserts a platform-specific debug trap instruction which causes
debuggers to break there.
< / p >
< p >
This function is only valid within function scope.
< / p >
2019-06-18 23:28:49 +01:00
{#header_close#}
{#header_open|@mulAdd#}
< pre > {#syntax#}@mulAdd(comptime T: type, a: T, b: T, c: T) T{#endsyntax#}< / pre >
< p >
2020-01-08 16:57:20 +00:00
Fused multiply add, similar to {#syntax#}(a * b) + c{#endsyntax#}, except
2019-06-18 23:28:49 +01:00
only rounds once, and is thus more accurate.
< / p >
2020-01-08 16:57:20 +00:00
< p >
Supports Floats and Vectors of floats.
< / p >
2018-12-15 01:21:23 +00:00
{#header_close#}
2019-04-03 15:00:39 +01:00
{#header_open|@byteSwap#}
2019-09-19 05:59:04 +01:00
< pre > {#syntax#}@byteSwap(comptime T: type, operand: T) T{#endsyntax#}< / pre >
2018-12-13 01:19:46 +00:00
< p > {#syntax#}T{#endsyntax#} must be an integer type with bit count evenly divisible by 8.< / p >
2019-09-19 05:59:04 +01:00
< p > {#syntax#}operand{#endsyntax#} may be an {#link|integer|Integers#} or {#link|vector|Vectors#}.< / p >
2018-12-13 01:19:46 +00:00
< p >
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.
< / p >
2019-09-19 05:59:04 +01:00
< p >
Note that for the purposes of memory layout with respect to endianness, the integer type should be
related to the number of bytes reported by {#link|@sizeOf#} bytes. This is demonstrated with
{#syntax#}u24{#endsyntax#}. {#syntax#}@sizeOf(u24) == 4{#endsyntax#}, which means that a
{#syntax#}u24{#endsyntax#} stored in memory takes 4 bytes, and those 4 bytes are what are swapped on
a little vs big endian system. On the other hand, if {#syntax#}T{#endsyntax#} is specified to
be {#syntax#}u24{#endsyntax#}, then only 3 bytes are reversed.
< / p >
2018-12-13 01:19:46 +00:00
{#header_close#}
2019-04-03 15:00:39 +01:00
{#header_open|@bitReverse#}
< pre > {#syntax#}@bitReverse(comptime T: type, integer: T) T{#endsyntax#}< / pre >
2019-01-02 21:47:47 +00:00
< p > {#syntax#}T{#endsyntax#} accepts any integer type.< / p >
< p >
Reverses the bitpattern of an integer value, including the sign bit if applicable.
< / p >
< p >
For example 0b10110110 ({#syntax#}u8 = 182{#endsyntax#}, {#syntax#}i8 = -74{#endsyntax#})
becomes 0b01101101 ({#syntax#}u8 = 109{#endsyntax#}, {#syntax#}i8 = 109{#endsyntax#}).
< / p >
{#header_close#}
2018-12-15 01:21:23 +00:00
{#header_open|@byteOffsetOf#}
2019-06-10 00:24:24 +01:00
< pre > {#syntax#}@byteOffsetOf(comptime T: type, comptime field_name: []const u8) comptime_int{#endsyntax#}< / pre >
2018-12-15 01:21:23 +00:00
< p >
Returns the byte offset of a field relative to its containing struct.
< / p >
{#see_also|@bitOffsetOf#}
{#header_close#}
2019-12-05 22:37:29 +00:00
{#header_open|@call#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@call(options: std.builtin.CallOptions, function: anytype, args: anytype) anytype{#endsyntax#}< / pre >
2019-12-05 22:37:29 +00:00
< p >
Calls a function, in the same way that invoking an expression with parentheses does:
< / p >
{#code_begin|test|call#}
const assert = @import("std").debug.assert;
test "noinline function call" {
assert(@call(.{}, add, .{3, 9}) == 12);
}
fn add(a: i32, b: i32) i32 {
return a + b;
}
{#code_end#}
< p >
{#syntax#}@call{#endsyntax#} allows more flexibility than normal function call syntax does. The
{#syntax#}CallOptions{#endsyntax#} struct is reproduced here:
< / p >
{#code_begin|syntax#}
pub const CallOptions = struct {
modifier: Modifier = .auto,
stack: ?[]align(std.Target.stack_align) u8 = null,
pub const Modifier = enum {
/// Equivalent to function call syntax.
auto,
2019-12-09 17:25:57 +00:00
/// Equivalent to async keyword used with function call syntax.
async_kw,
2019-12-05 22:37:29 +00:00
/// Prevents tail call optimization. This guarantees that the return
/// address will point to the callsite, as opposed to the callsite's
/// callsite. If the call is otherwise required to be tail-called
/// or inlined, a compile error is emitted instead.
never_tail,
/// Guarantees that the call will not be inlined. If the call is
/// otherwise required to be inlined, a compile error is emitted instead.
never_inline,
2019-12-06 20:25:00 +00:00
/// Asserts that the function call will not suspend. This allows a
/// non-async function to call an async function.
no_async,
2019-12-05 22:37:29 +00:00
/// Guarantees that the call will be generated with tail call optimization.
/// If this is not possible, a compile error is emitted instead.
always_tail,
/// Guarantees that the call will inlined at the callsite.
/// If this is not possible, a compile error is emitted instead.
always_inline,
/// Evaluates the call at compile-time. If the call cannot be completed at
/// compile-time, a compile error is emitted instead.
compile_time,
};
};
{#code_end#}
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@cDefine#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@cDefine(comptime name: []u8, value){#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
This function can only occur inside {#syntax#}@cImport{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2018-09-14 15:35:03 +01:00
This appends < code > #define $name $value< / code > to the {#syntax#}@cImport{#endsyntax#}
2017-11-07 08:22:27 +00:00
temporary buffer.
< / p >
< p >
To define without a value, like this:
< / p >
< pre > < code class = "c" > #define _GNU_SOURCE< / code > < / pre >
< p >
Use the void value, like this:
< / p >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@cDefine("_GNU_SOURCE", {}){#endsyntax#}< / pre >
2018-01-17 05:22:33 +00:00
{#see_also|Import from C Header File|@cInclude|@cImport|@cUndef|void#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@cImport#}
2019-03-13 17:04:55 +00:00
< pre > {#syntax#}@cImport(expression) type{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2019-03-13 17:04:55 +00:00
This function parses C code and imports the functions, types, variables,
and compatible macro definitions into a new empty struct type, and then
returns that type.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2018-09-14 15:35:03 +01:00
{#syntax#}expression{#endsyntax#} is interpreted at compile time. The builtin functions
{#syntax#}@cInclude{#endsyntax#}, {#syntax#}@cDefine{#endsyntax#}, and {#syntax#}@cUndef{#endsyntax#} work
2017-11-07 08:22:27 +00:00
within this expression, appending to a temporary buffer which is then parsed as C code.
< / p >
2018-02-01 01:18:47 +00:00
< p >
2018-09-14 15:35:03 +01:00
Usually you should only have one {#syntax#}@cImport{#endsyntax#} in your entire application, because it saves the compiler
2018-02-01 01:18:47 +00:00
from invoking clang multiple times, and prevents inline functions from being duplicated.
< / p >
< p >
2018-09-14 15:35:03 +01:00
Reasons for having multiple {#syntax#}@cImport{#endsyntax#} expressions would be:
2018-02-01 01:18:47 +00:00
< / p >
< ul >
2018-09-14 15:35:03 +01:00
< li > To avoid a symbol collision, for example if foo.h and bar.h both < code > #define CONNECTION_COUNT< / code > < / li >
2018-02-01 01:18:47 +00:00
< li > To analyze the C code with different preprocessor defines< / li >
< / ul >
2018-01-17 05:22:33 +00:00
{#see_also|Import from C Header File|@cInclude|@cDefine|@cUndef#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@cInclude#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@cInclude(comptime path: []u8){#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
This function can only occur inside {#syntax#}@cImport{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2019-12-05 21:38:59 +00:00
This appends < code > #include < $path> \n< / code > to the {#syntax#}c_import{#endsyntax#}
2017-11-07 08:22:27 +00:00
temporary buffer.
< / p >
2018-01-17 05:22:33 +00:00
{#see_also|Import from C Header File|@cImport|@cDefine|@cUndef#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@clz#}
2019-05-16 21:32:24 +01:00
< pre > {#syntax#}@clz(comptime T: type, integer: T){#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2019-09-19 00:34:40 +01:00
This function counts the number of most-significant (leading in a big-Endian sense) zeroes in {#syntax#}integer{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2019-05-16 21:32:24 +01:00
If {#syntax#}integer{#endsyntax#} is known at {#link|comptime#},
the return type is {#syntax#}comptime_int{#endsyntax#}.
2019-04-03 15:00:39 +01:00
Otherwise, the return type is an unsigned integer with the minimum number
of bits that can represent the bit count of the integer type.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2019-05-16 21:32:24 +01:00
If {#syntax#}integer{#endsyntax#} is zero, {#syntax#}@clz{#endsyntax#} returns the bit width
of integer type {#syntax#}T{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
2018-07-07 05:25:32 +01:00
{#see_also|@ctz|@popCount#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-04-18 17:16:42 +01:00
{#header_open|@cmpxchgStrong#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@cmpxchgStrong(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-04-18 17:16:42 +01:00
This function performs a strong atomic compare exchange operation. It's the equivalent of this code,
except atomic:
< / p >
{#code_begin|syntax#}
2018-05-31 15:56:59 +01:00
fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T {
2018-05-18 04:21:44 +01:00
const old_value = ptr.*;
2018-04-18 17:16:42 +01:00
if (old_value == expected_value) {
2018-05-18 04:21:44 +01:00
ptr.* = new_value;
2018-04-18 17:16:42 +01:00
return null;
} else {
return old_value;
}
}
{#code_end#}
< p >
If you are using cmpxchg in a loop, {#link|@cmpxchgWeak#} is the better choice, because it can be implemented
more efficiently in machine instructions.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2020-09-04 19:41:34 +01:00
{#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float,
2020-03-11 11:29:17 +00:00
an integer or an enum.
2017-11-07 08:22:27 +00:00
< / p >
2020-09-04 20:49:14 +01:00
< p > {#syntax#}@typeInfo(@TypeOf(ptr)).Pointer.alignment{#endsyntax#} must be {#syntax#}>= @sizeOf(T).{#endsyntax#}< / p >
2018-04-18 17:16:42 +01:00
{#see_also|Compile Variables|cmpxchgWeak#}
{#header_close#}
{#header_open|@cmpxchgWeak#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@cmpxchgWeak(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T{#endsyntax#}< / pre >
2018-04-18 17:16:42 +01:00
< p >
This function performs a weak atomic compare exchange operation. It's the equivalent of this code,
except atomic:
< / p >
{#code_begin|syntax#}
2018-05-31 15:56:59 +01:00
fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T {
2018-05-18 04:21:44 +01:00
const old_value = ptr.*;
2018-04-18 17:16:42 +01:00
if (old_value == expected_value and usuallyTrueButSometimesFalse()) {
2018-05-18 04:21:44 +01:00
ptr.* = new_value;
2018-04-18 17:16:42 +01:00
return null;
} else {
return old_value;
}
}
{#code_end#}
< p >
2018-09-14 15:35:03 +01:00
If you are using cmpxchg in a loop, the sporadic failure will be no problem, and {#syntax#}cmpxchgWeak{#endsyntax#}
2018-04-18 17:16:42 +01:00
is the better choice, because it can be implemented more efficiently in machine instructions.
However if you need a stronger guarantee, use {#link|@cmpxchgStrong#}.
< / p >
< p >
2020-09-04 19:41:34 +01:00
{#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float,
2020-03-11 11:29:17 +00:00
an integer or an enum.
2018-04-18 17:16:42 +01:00
< / p >
2020-09-04 20:49:14 +01:00
< p > {#syntax#}@typeInfo(@TypeOf(ptr)).Pointer.alignment{#endsyntax#} must be {#syntax#}>= @sizeOf(T).{#endsyntax#}< / p >
2018-04-18 17:16:42 +01:00
{#see_also|Compile Variables|cmpxchgStrong#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@compileError#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@compileError(comptime msg: []u8){#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
This function, when semantically analyzed, causes a compile error with the
2018-09-14 15:35:03 +01:00
message {#syntax#}msg{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
< p >
There are several ways that code avoids being semantically checked, such as
2018-09-14 15:35:03 +01:00
using {#syntax#}if{#endsyntax#} or {#syntax#}switch{#endsyntax#} with compile time constants,
and {#syntax#}comptime{#endsyntax#} functions.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@compileLog#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@compileLog(args: ...){#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
This function prints the arguments passed to it at compile-time.
< / p >
< p >
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.
< / p >
< p >
This function can be used to do "printf debugging" on
compile-time executing code.
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|found compile log statement#}
2020-06-19 10:38:22 +01:00
const print = @import("std").debug.print;
2017-11-07 08:22:27 +00:00
2018-01-19 08:03:20 +00:00
const num1 = blk: {
2017-11-07 08:22:27 +00:00
var val1: i32 = 99;
2019-02-22 15:56:49 +00:00
@compileLog("comptime val1 = ", val1);
2017-11-07 08:22:27 +00:00
val1 = val1 + 1;
2018-01-19 08:03:20 +00:00
break :blk val1;
2017-11-07 08:22:27 +00:00
};
2018-01-19 08:03:20 +00:00
test "main" {
2019-02-22 15:56:49 +00:00
@compileLog("comptime in main");
2017-11-07 08:22:27 +00:00
2020-06-19 10:38:22 +01:00
print("Runtime in main, num1 = {}.\n", .{num1});
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
will ouput:
< / p >
< p >
2019-02-22 15:56:49 +00:00
If all {#syntax#}@compileLog{#endsyntax#} calls are removed or
2017-11-07 08:22:27 +00:00
not encountered by analysis, the
program compiles successfully and the generated executable prints:
2019-02-22 15:56:49 +00:00
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
2020-06-19 10:38:22 +01:00
const print = @import("std").debug.print;
2018-01-19 08:03:20 +00:00
const num1 = blk: {
var val1: i32 = 99;
val1 = val1 + 1;
break :blk val1;
};
test "main" {
2020-06-19 10:38:22 +01:00
print("Runtime in main, num1 = {}.\n", .{num1});
2018-01-19 08:03:20 +00:00
}
{#code_end#}
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-19 08:03:20 +00:00
{#header_open|@ctz#}
2019-05-16 21:32:24 +01:00
< pre > {#syntax#}@ctz(comptime T: type, integer: T){#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2019-09-19 00:34:40 +01:00
This function counts the number of least-significant (trailing in a big-Endian sense) zeroes in {#syntax#}integer{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2019-05-16 21:32:24 +01:00
If {#syntax#}integer{#endsyntax#} is known at {#link|comptime#},
the return type is {#syntax#}comptime_int{#endsyntax#}.
2019-04-03 15:00:39 +01:00
Otherwise, the return type is an unsigned integer with the minimum number
of bits that can represent the bit count of the integer type.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2019-05-16 21:32:24 +01:00
If {#syntax#}integer{#endsyntax#} is zero, {#syntax#}@ctz{#endsyntax#} returns
the bit width of integer type {#syntax#}T{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
2018-07-07 05:25:32 +01:00
{#see_also|@clz|@popCount#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
{#header_open|@cUndef#}
< pre > {#syntax#}@cUndef(comptime name: []u8){#endsyntax#}< / pre >
< p >
This function can only occur inside {#syntax#}@cImport{#endsyntax#}.
< / p >
< p >
This appends < code > #undef $name< / code > to the {#syntax#}@cImport{#endsyntax#}
temporary buffer.
< / p >
{#see_also|Import from C Header File|@cImport|@cDefine|@cInclude#}
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@divExact#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@divExact(numerator: T, denominator: T) T{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
Exact division. Caller guarantees {#syntax#}denominator != 0{#endsyntax#} and
{#syntax#}@divTrunc(numerator, denominator) * denominator == numerator{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
< ul >
2018-09-14 15:35:03 +01:00
< li > {#syntax#}@divExact(6, 3) == 2{#endsyntax#}< / li >
< li > {#syntax#}@divExact(a, b) * b == a{#endsyntax#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
2018-09-14 15:35:03 +01:00
< p > For a function that returns a possible error code, use {#syntax#}@import("std").math.divExact{#endsyntax#}.< / p >
2018-01-17 05:22:33 +00:00
{#see_also|@divTrunc|@divFloor#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@divFloor#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@divFloor(numerator: T, denominator: T) T{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
Floored division. Rounds toward negative infinity. For unsigned integers it is
2018-09-14 15:35:03 +01:00
the same as {#syntax#}numerator / denominator{#endsyntax#}. Caller guarantees {#syntax#}denominator != 0{#endsyntax#} and
2020-02-24 21:21:11 +00:00
{#syntax#}!(@typeInfo(T) == .Int and T.is_signed and numerator == std.math.minInt(T) and denominator == -1){#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
< ul >
2018-09-14 15:35:03 +01:00
< li > {#syntax#}@divFloor(-5, 3) == -2{#endsyntax#}< / li >
< li > {#syntax#}@divFloor(a, b) + @mod(a, b) == a{#endsyntax#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
2018-09-14 15:35:03 +01:00
< p > For a function that returns a possible error code, use {#syntax#}@import("std").math.divFloor{#endsyntax#}.< / p >
2018-01-17 05:22:33 +00:00
{#see_also|@divTrunc|@divExact#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@divTrunc#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@divTrunc(numerator: T, denominator: T) T{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
Truncated division. Rounds toward zero. For unsigned integers it is
2018-09-14 15:35:03 +01:00
the same as {#syntax#}numerator / denominator{#endsyntax#}. Caller guarantees {#syntax#}denominator != 0{#endsyntax#} and
2020-02-24 21:21:11 +00:00
{#syntax#}!(@typeInfo(T) == .Int and T.is_signed and numerator == std.math.minInt(T) and denominator == -1){#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
< ul >
2018-09-14 15:35:03 +01:00
< li > {#syntax#}@divTrunc(-5, 3) == -1{#endsyntax#}< / li >
< li > {#syntax#}@divTrunc(a, b) + @rem(a, b) == a{#endsyntax#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
2018-09-14 15:35:03 +01:00
< p > For a function that returns a possible error code, use {#syntax#}@import("std").math.divTrunc{#endsyntax#}.< / p >
2018-01-17 05:22:33 +00:00
{#see_also|@divFloor|@divExact#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@embedFile#}
2020-03-06 21:01:26 +00:00
< pre > {#syntax#}@embedFile(comptime path: []const u8) *const [X:0]u8{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2020-03-06 21:01:26 +00:00
This function returns a compile time constant pointer to null-terminated,
fixed-size array with length equal to the byte count of the file given by
{#syntax#}path{#endsyntax#}. The contents of the array are the contents of the file.
This is equivalent to a {#link|string literal|String Literals and Character Literals#}
with the file contents.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2018-09-14 15:35:03 +01:00
{#syntax#}path{#endsyntax#} is absolute or relative to the current file, just like {#syntax#}@import{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 05:22:33 +00:00
{#see_also|@import#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 20:01:42 +01:00
2018-06-19 08:50:38 +01:00
{#header_open|@enumToInt#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@enumToInt(enum_or_tagged_union: anytype) anytype{#endsyntax#}< / pre >
2018-06-19 08:50:38 +01:00
< p >
2019-02-18 17:56:17 +00:00
Converts an enumeration value into its integer tag type. When a tagged union is passed,
the tag value is used as the enumeration value.
2018-06-19 08:50:38 +01:00
< / p >
2018-09-13 18:29:43 +01:00
< p >
2019-02-18 17:56:17 +00:00
If there is only one possible enum value, the resut is a {#syntax#}comptime_int{#endsyntax#}
2018-09-13 18:29:43 +01:00
known at {#link|comptime#}.
< / p >
2018-06-19 08:50:38 +01:00
{#see_also|@intToEnum#}
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@errorName#}
2018-11-19 18:20:39 +00:00
< pre > {#syntax#}@errorName(err: anyerror) []const u8{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-11-19 18:20:39 +00:00
This function returns the string representation of an error. The string representation
of {#syntax#}error.OutOfMem{#endsyntax#} is {#syntax#}"OutOfMem"{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2018-09-14 15:35:03 +01:00
If there are no calls to {#syntax#}@errorName{#endsyntax#} in an entire application,
2018-11-19 18:20:39 +00:00
or all calls have a compile-time known value for {#syntax#}err{#endsyntax#}, then no
2017-11-07 08:22:27 +00:00
error name table will be generated.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 23:48:29 +01:00
2018-01-17 04:19:05 +00:00
{#header_open|@errorReturnTrace#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@errorReturnTrace() ?*builtin.StackTrace{#endsyntax#}< / pre >
2018-01-15 05:01:02 +00:00
< p >
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 `null`.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 20:01:42 +01:00
2018-06-18 23:48:29 +01:00
{#header_open|@errorToInt#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@errorToInt(err: anytype) std.meta.IntType(false, @sizeOf(anyerror) * 8){#endsyntax#}< / pre >
2018-06-18 23:48:29 +01:00
< p >
Supports the following types:
< / p >
< ul >
2018-11-19 18:20:39 +00:00
< li > {#link|The Global Error Set#}< / li >
< li > {#link|Error Set Type#}< / li >
< li > {#link|Error Union Type#}< / li >
2018-06-18 23:48:29 +01:00
< / ul >
< p >
Converts an error to the integer representation of an error.
< / p >
< p >
It is generally recommended to avoid this
cast, as the integer representation of an error is not stable across source code changes.
< / p >
{#see_also|@intToError#}
{#header_close#}
2018-12-15 01:21:23 +00:00
{#header_open|@errSetCast#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@errSetCast(comptime T: DestType, value: anytype) DestType{#endsyntax#}< / pre >
2018-12-15 01:21:23 +00:00
< p >
Converts an error value from one error set to another error set. Attempting to convert an error
which is not in the destination error set results in safety-protected {#link|Undefined Behavior#}.
< / p >
{#header_close#}
2018-06-18 20:01:42 +01:00
{#header_open|@export#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@export(target: anytype, comptime options: std.builtin.ExportOptions) void{#endsyntax#}< / pre >
2018-06-18 20:01:42 +01:00
< p >
Creates a symbol in the output object file.
< / p >
2019-03-13 15:54:56 +00:00
< p >
This function can be called from a {#link|comptime#} block to conditionally export symbols.
When {#syntax#}target{#endsyntax#} is a function with the C calling convention and
2020-01-09 09:36:51 +00:00
{#syntax#}options.linkage{#endsyntax#} is {#syntax#}Strong{#endsyntax#}, this is equivalent to
2019-03-13 15:54:56 +00:00
the {#syntax#}export{#endsyntax#} keyword used on a function:
< / p >
{#code_begin|obj#}
comptime {
2020-01-09 09:36:51 +00:00
@export(internalName, .{ .name = "foo", .linkage = .Strong });
2019-03-13 15:54:56 +00:00
}
2020-02-18 22:35:08 +00:00
fn internalName() callconv(.C) void {}
2019-03-13 15:54:56 +00:00
{#code_end#}
< p > This is equivalent to:< / p >
{#code_begin|obj#}
export fn foo() void {}
{#code_end#}
< p > Note that even when using {#syntax#}export{#endsyntax#}, {#syntax#}@"foo"{#endsyntax#} syntax can
be used to choose any string for the symbol name:< / p >
{#code_begin|obj#}
export fn @"A function name that is a complete sentence."() void {}
{#code_end#}
< p >
When looking at the resulting object, you can see the symbol is used verbatim:
< / p >
2020-07-27 15:10:55 +01:00
< pre > < code > 00000000000001f0 T A function name that is a complete sentence.< / code > < / pre >
2019-03-13 15:54:56 +00:00
{#see_also|Exporting a C Library#}
2018-06-18 20:01:42 +01:00
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@fence#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@fence(order: AtomicOrder){#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
The {#syntax#}fence{#endsyntax#} function is used to introduce happens-before edges between operations.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2018-09-14 15:35:03 +01:00
{#syntax#}AtomicOrder{#endsyntax#} can be found with {#syntax#}@import("builtin").AtomicOrder{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 05:22:33 +00:00
{#see_also|Compile Variables#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 08:07:16 +01:00
{#header_open|@field#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@field(lhs: anytype, comptime field_name: []const u8) (field){#endsyntax#}< / pre >
2019-09-04 18:02:31 +01:00
< p > Performs field access by a compile-time string.
2018-09-14 15:35:03 +01:00
< / p >
2019-09-04 18:02:31 +01:00
{#code_begin|test#}
const std = @import("std");
const Point = struct {
x: u32,
y: u32
};
test "field access by string" {
const assert = std.debug.assert;
var p = Point {.x = 0, .y = 0};
@field(p, "x") = 4;
@field(p, "y") = @field(p, "x") + 1;
assert(@field(p, "x") == 4);
assert(@field(p, "y") == 5);
}
{#code_end#}
2018-06-18 08:07:16 +01:00
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@fieldParentPtr#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@fieldParentPtr(comptime ParentType: type, comptime field_name: []const u8,
field_ptr: *T) *ParentType{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
Given a pointer to a field, returns the base pointer of a struct.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 08:07:16 +01:00
{#header_open|@floatCast#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@floatCast(comptime DestType: type, value: anytype) DestType{#endsyntax#}< / pre >
2018-06-18 08:07:16 +01:00
< p >
Convert from one float type to another. This cast is safe, but may cause the
numeric value to lose precision.
< / p >
{#header_close#}
{#header_open|@floatToInt#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@floatToInt(comptime DestType: type, float: anytype) DestType{#endsyntax#}< / pre >
2018-06-18 08:07:16 +01:00
< p >
Converts the integer part of a floating point number to the destination type.
< / p >
2018-06-19 21:06:10 +01:00
< p >
If the integer part of the floating point number cannot fit in the destination type,
it invokes safety-checked {#link|Undefined Behavior#}.
< / p >
{#see_also|@intToFloat#}
2018-06-18 08:07:16 +01:00
{#header_close#}
2019-08-15 21:46:43 +01:00
{#header_open|@frame#}
< pre > {#syntax#}@frame() *@Frame(func){#endsyntax#}< / pre >
< p >
This function returns a pointer to the frame for a given function. This type
2019-11-08 20:56:21 +00:00
can be {#link|coerced|Type Coercion#} to {#syntax#}anyframe->T{#endsyntax#} and
2019-08-15 21:46:43 +01:00
to {#syntax#}anyframe{#endsyntax#}, where {#syntax#}T{#endsyntax#} is the return type
of the function in scope.
< / p >
< p >
This function does not mark a suspension point, but it does cause the function in scope
to become an {#link|async function|Async Functions#}.
< / p >
{#header_close#}
{#header_open|@Frame#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@Frame(func: anytype) type{#endsyntax#}< / pre >
2019-08-15 21:46:43 +01:00
< p >
This function returns the frame type of a function. This works for {#link|Async Functions#}
as well as any function without a specific calling convention.
< / p >
< p >
This type is suitable to be used as the return type of {#link|async|Async and Await#} which
allows one to, for example, heap-allocate an async function frame:
< / p >
{#code_begin|test#}
const std = @import("std");
test "heap allocated frame" {
2019-11-25 22:25:06 +00:00
const frame = try std.heap.page_allocator.create(@Frame(func));
2019-08-15 21:46:43 +01:00
frame.* = async func();
}
fn func() void {
suspend;
}
{#code_end#}
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@frameAddress#}
2019-03-02 20:34:58 +00:00
< pre > {#syntax#}@frameAddress() usize{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
This function returns the base pointer of the current stack frame.
< / p >
< p >
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.
< / p >
< p >
This function is only valid within function scope.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2019-08-15 21:46:43 +01:00
{#header_open|@frameSize#}
< pre > {#syntax#}@frameSize() usize{#endsyntax#}< / pre >
2018-08-02 09:47:39 +01:00
< p >
2019-08-15 21:46:43 +01:00
This is the same as {#syntax#}@sizeOf(@Frame(func)){#endsyntax#}, where {#syntax#}func{#endsyntax#}
may be runtime-known.
2018-08-02 09:47:39 +01:00
< / p >
< p >
2019-08-15 21:46:43 +01:00
This function is typically used in conjunction with {#link|@asyncCall#}.
2018-08-02 09:47:39 +01:00
< / p >
{#header_close#}
2018-12-15 01:21:23 +00:00
2019-05-26 21:21:03 +01:00
{#header_open|@hasDecl#}
2019-09-29 22:28:30 +01:00
< pre > {#syntax#}@hasDecl(comptime Container: type, comptime name: []const u8) bool{#endsyntax#}< / pre >
2019-05-26 21:21:03 +01:00
< p >
Returns whether or not a {#link|struct#}, {#link|enum#}, or {#link|union#} has a declaration
matching {#syntax#}name{#endsyntax#}.
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
const Foo = struct {
nope: i32,
pub var blah = "xxx";
const hi = 1;
};
test "@hasDecl" {
assert(@hasDecl(Foo, "blah"));
// Even though `hi` is private, @hasDecl returns true because this test is
// in the same file scope as Foo. It would return false if Foo was declared
// in a different file.
assert(@hasDecl(Foo, "hi"));
// @hasDecl is for declarations; not fields.
assert(!@hasDecl(Foo, "nope"));
assert(!@hasDecl(Foo, "nope1234"));
}
{#code_end#}
2019-07-02 21:52:55 +01:00
{#see_also|@hasField#}
{#header_close#}
{#header_open|@hasField#}
2019-09-29 22:28:30 +01:00
< pre > {#syntax#}@hasField(comptime Container: type, comptime name: []const u8) bool{#endsyntax#}< / pre >
2019-07-02 21:52:55 +01:00
< p > Returns whether the field name of a struct, union, or enum exists.< / p >
< p >
The result is a compile time constant.
< / p >
< p >
It does not include functions, variables, or constants.
< / p >
{#see_also|@hasDecl#}
2019-05-26 21:21:03 +01:00
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@import#}
2019-03-13 17:04:55 +00:00
< pre > {#syntax#}@import(comptime path: []u8) type{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2019-03-13 17:04:55 +00:00
This function finds a zig file corresponding to {#syntax#}path{#endsyntax#} and adds it to the build,
if it is not already added.
< / p >
< p >
Zig source files are implicitly structs, with a name equal to the file's basename with the extension
truncated. {#syntax#}@import{#endsyntax#} returns the struct type corresponding to the file.
< / p >
< p >
Declarations which have the {#syntax#}pub{#endsyntax#} keyword may be referenced from a different
source file than the one they are declared in.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2020-07-01 20:44:18 +01:00
{#syntax#}path{#endsyntax#} can be a relative path or it can be the name of a package.
2019-03-13 17:04:55 +00:00
If it is a relative path, it is relative to the file that contains the {#syntax#}@import{#endsyntax#}
2017-11-07 08:22:27 +00:00
function call.
< / p >
< p >
The following packages are always available:
< / p >
< ul >
2018-09-14 15:35:03 +01:00
< li > {#syntax#}@import("std"){#endsyntax#} - Zig Standard Library< / li >
2019-03-13 17:04:55 +00:00
< li > {#syntax#}@import("builtin"){#endsyntax#} - Compiler-provided types and variables.
The command < code > zig builtin< / code > outputs the source to stdout for reference.
< / li >
2017-11-07 08:22:27 +00:00
< / ul >
2018-01-17 05:22:33 +00:00
{#see_also|Compile Variables|@embedFile#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-06-18 08:07:16 +01:00
{#header_open|@intCast#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@intCast(comptime DestType: type, int: anytype) DestType{#endsyntax#}< / pre >
2018-06-18 08:07:16 +01:00
< p >
Converts an integer to another integer while keeping the same numerical value.
Attempting to convert a number which is out of range of the destination type results in
2018-06-18 23:48:29 +01:00
safety-protected {#link|Undefined Behavior#}.
< / p >
2019-11-29 17:41:07 +00:00
< p >
If {#syntax#}T{#endsyntax#} is {#syntax#}comptime_int{#endsyntax#},
then this is semantically equivalent to {#link|Type Coercion#}.
< / p >
2018-06-18 23:48:29 +01:00
{#header_close#}
2018-06-19 08:50:38 +01:00
{#header_open|@intToEnum#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@intToEnum(comptime DestType: type, int_value: @TagType(DestType)) DestType{#endsyntax#}< / pre >
2018-06-19 08:50:38 +01:00
< p >
Converts an integer into an {#link|enum#} value.
< / p >
< p >
Attempting to convert an integer which represents no value in the chosen enum type invokes
safety-checked {#link|Undefined Behavior#}.
< / p >
{#see_also|@enumToInt#}
{#header_close#}
2018-06-18 23:48:29 +01:00
{#header_open|@intToError#}
2020-02-24 21:39:03 +00:00
< pre > {#syntax#}@intToError(value: std.meta.IntType(false, @sizeOf(anyerror) * 8)) anyerror{#endsyntax#}< / pre >
2018-06-18 23:48:29 +01:00
< p >
2018-11-19 18:20:39 +00:00
Converts from the integer representation of an error into {#link|The Global Error Set#} type.
2018-06-18 23:48:29 +01:00
< / p >
< p >
It is generally recommended to avoid this
cast, as the integer representation of an error is not stable across source code changes.
< / p >
< p >
Attempting to convert an integer that does not correspond to any error results in
safety-protected {#link|Undefined Behavior#}.
2018-06-18 08:07:16 +01:00
< / p >
2018-06-18 23:48:29 +01:00
{#see_also|@errorToInt#}
2018-06-18 08:07:16 +01:00
{#header_close#}
{#header_open|@intToFloat#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@intToFloat(comptime DestType: type, int: anytype) DestType{#endsyntax#}< / pre >
2018-06-18 08:07:16 +01:00
< p >
Converts an integer to the closest floating point representation. To convert the other way, use {#link|@floatToInt#}. This cast is always safe.
< / p >
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@intToPtr#}
2019-03-25 16:55:45 +00:00
< pre > {#syntax#}@intToPtr(comptime DestType: type, address: usize) DestType{#endsyntax#}< / pre >
< p >
Converts an integer to a {#link|pointer|Pointers#}. To convert the other way, use {#link|@ptrToInt#}.
< / p >
2017-11-07 08:22:27 +00:00
< p >
2019-03-25 16:55:45 +00:00
If the destination pointer type does not allow address zero and {#syntax#}address{#endsyntax#}
is zero, this invokes safety-checked {#link|Undefined Behavior#}.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 08:07:16 +01:00
2018-01-17 04:19:05 +00:00
{#header_open|@memcpy#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@memcpy(noalias dest: [*]u8, noalias source: [*]const u8, byte_count: usize){#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
This function copies bytes from one region of memory to another. {#syntax#}dest{#endsyntax#} and
{#syntax#}source{#endsyntax#} are both pointers and must not overlap.
2017-11-07 08:22:27 +00:00
< / p >
< p >
This function is a low level intrinsic with no safety mechanisms. Most code
should not use this function, instead using something like this:
< / p >
2019-01-30 02:47:26 +00:00
< pre > {#syntax#}for (source[0..byte_count]) |b, i| dest[i] = b;{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
The optimizer is intelligent enough to turn the above snippet into a memcpy.
< / p >
< p > There is also a standard library function for this:< / p >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}const mem = @import("std").mem;
2019-01-30 02:47:26 +00:00
mem.copy(u8, dest[0..byte_count], source[0..byte_count]);{#endsyntax#}< / pre >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@memset#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@memset(dest: [*]u8, c: u8, byte_count: usize){#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
This function sets a region of memory to {#syntax#}c{#endsyntax#}. {#syntax#}dest{#endsyntax#} is a pointer.
2017-11-07 08:22:27 +00:00
< / p >
< p >
This function is a low level intrinsic with no safety mechanisms. Most
code should not use this function, instead using something like this:
< / p >
2019-01-30 02:47:26 +00:00
< pre > {#syntax#}for (dest[0..byte_count]) |*b| b.* = c;{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
The optimizer is intelligent enough to turn the above snippet into a memset.
< / p >
< p > There is also a standard library function for this:< / p >
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}const mem = @import("std").mem;
mem.set(u8, dest, c);{#endsyntax#}< / pre >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2020-06-05 08:27:52 +01:00
{#header_open|@wasmMemorySize#}
< pre > {#syntax#}@wasmMemorySize(index: u32) u32{#endsyntax#}< / pre >
< p >
This function returns the size of the Wasm memory identified by {#syntax#}index{#endsyntax#} as
an unsigned value in units of Wasm pages. Note that each Wasm page is 64KB in size.
< / p >
< p >
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
2020-06-05 09:16:41 +01:00
something like {#syntax#}@import("std").heap.WasmPageAllocator{#endsyntax#}.
2020-06-05 08:27:52 +01:00
< / p >
{#see_also|@wasmMemoryGrow#}
{#header_close#}
{#header_open|@wasmMemoryGrow#}
< pre > {#syntax#}@wasmMemoryGrow(index: u32, delta: u32) i32{#endsyntax#}< / pre >
< p >
This function increases the size of the Wasm memory identified by {#syntax#}index{#endsyntax#} by
{#syntax#}delta{#endsyntax#} in units of unsigned number of Wasm pages. Note that each Wasm page
is 64KB in size. On success, returns previous memory size; on failure, if the allocation fails,
returns -1.
< / p >
< p >
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
2020-06-05 09:16:41 +01:00
something like {#syntax#}@import("std").heap.WasmPageAllocator{#endsyntax#}.
2020-06-05 08:27:52 +01:00
< / p >
{#code_begin|test#}
const std = @import("std");
2020-06-05 09:16:41 +01:00
const builtin = @import("builtin");
2020-06-05 08:27:52 +01:00
const assert = std.debug.assert;
test "@wasmMemoryGrow" {
2020-06-05 09:16:41 +01:00
if (builtin.arch != .wasm32) return error.SkipZigTest;
2020-06-05 08:27:52 +01:00
var prev = @wasmMemorySize(0);
assert(prev == @wasmMemoryGrow(0, 1));
assert(prev + 1 == @wasmMemorySize(0));
}
{#code_end#}
{#see_also|@wasmMemorySize#}
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@mod#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@mod(numerator: T, denominator: T) T{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
Modulus division. For unsigned integers this is the same as
2018-10-05 15:21:08 +01:00
{#syntax#}numerator % denominator{#endsyntax#}. Caller guarantees {#syntax#}denominator > 0{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
< ul >
2018-09-14 15:35:03 +01:00
< li > {#syntax#}@mod(-5, 3) == 1{#endsyntax#}< / li >
< li > {#syntax#}@divFloor(a, b) + @mod(a, b) == a{#endsyntax#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
2018-09-14 15:35:03 +01:00
< p > For a function that returns an error code, see {#syntax#}@import("std").math.mod{#endsyntax#}.< / p >
2018-01-17 05:22:33 +00:00
{#see_also|@rem#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@mulWithOverflow#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@mulWithOverflow(comptime T: type, a: T, b: T, result: *T) bool{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
Performs {#syntax#}result.* = a * b{#endsyntax#}. If overflow or underflow occurs,
stores the overflowed bits in {#syntax#}result{#endsyntax#} and returns {#syntax#}true{#endsyntax#}.
If no overflow or underflow occurs, returns {#syntax#}false{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@panic#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@panic(message: []const u8) noreturn{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
Invokes the panic handler function. By default the panic handler function
2018-09-14 15:35:03 +01:00
calls the public {#syntax#}panic{#endsyntax#} function exposed in the root source file, or
2020-04-12 10:41:00 +01:00
if there is not one specified, the {#syntax#}std.builtin.default_panic{#endsyntax#}
function from {#syntax#}std/builtin.zig{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
2018-09-14 15:35:03 +01:00
< p > Generally it is better to use {#syntax#}@import("std").debug.panic{#endsyntax#}.
However, {#syntax#}@panic{#endsyntax#} can be useful for 2 scenarios:
2017-11-07 08:22:27 +00:00
< / p >
< ul >
< li > From library code, calling the programmer's panic function if they exposed one in the root source file.< / li >
< li > When mixing C and Zig code, calling the canonical panic implementation across multiple .o files.< / li >
< / ul >
2018-01-17 05:22:33 +00:00
{#see_also|Root Source File#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-07-07 05:25:32 +01:00
{#header_open|@popCount#}
2019-05-16 21:32:24 +01:00
< pre > {#syntax#}@popCount(comptime T: type, integer: T){#endsyntax#}< / pre >
2018-07-07 05:25:32 +01:00
< p > Counts the number of bits set in an integer.< / p >
< p >
2019-05-16 21:32:24 +01:00
If {#syntax#}integer{#endsyntax#} is known at {#link|comptime#},
the return type is {#syntax#}comptime_int{#endsyntax#}.
2018-07-07 05:25:32 +01:00
Otherwise, the return type is an unsigned integer with the minimum number
of bits that can represent the bit count of the integer type.
< / p >
{#see_also|@ctz|@clz#}
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@ptrCast#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@ptrCast(comptime DestType: type, value: anytype) DestType{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
Converts a pointer of one type to a pointer of another type.
< / p >
2019-02-14 23:59:20 +00:00
< p >
{#link|Optional Pointers#} are allowed. Casting an optional pointer which is {#link|null#}
to a non-optional pointer invokes safety-checked {#link|Undefined Behavior#}.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@ptrToInt#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@ptrToInt(value: anytype) usize{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
Converts {#syntax#}value{#endsyntax#} to a {#syntax#}usize{#endsyntax#} which is the address of the pointer. {#syntax#}value{#endsyntax#} can be one of these types:
2017-11-07 08:22:27 +00:00
< / p >
< ul >
2018-09-14 15:35:03 +01:00
< li > {#syntax#}*T{#endsyntax#}< / li >
< li > {#syntax#}?*T{#endsyntax#}< / li >
< li > {#syntax#}fn(){#endsyntax#}< / li >
< li > {#syntax#}?fn(){#endsyntax#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
2018-01-23 04:06:07 +00:00
< p > To convert the other way, use {#link|@intToPtr#}< / p >
2017-11-07 08:22:27 +00:00
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@rem#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@rem(numerator: T, denominator: T) T{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
Remainder division. For unsigned integers this is the same as
2018-09-14 15:35:03 +01:00
{#syntax#}numerator % denominator{#endsyntax#}. Caller guarantees {#syntax#}denominator > 0{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
< ul >
2018-09-14 15:35:03 +01:00
< li > {#syntax#}@rem(-5, 3) == -2{#endsyntax#}< / li >
< li > {#syntax#}@divTrunc(a, b) + @rem(a, b) == a{#endsyntax#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
2018-09-14 15:35:03 +01:00
< p > For a function that returns an error code, see {#syntax#}@import("std").math.rem{#endsyntax#}.< / p >
2018-01-17 05:22:33 +00:00
{#see_also|@mod#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@returnAddress#}
2019-03-02 20:34:58 +00:00
< pre > {#syntax#}@returnAddress() usize{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2019-03-02 20:34:58 +00:00
This function returns the address of the next machine code instruction that will be executed
when the current function returns.
2017-11-07 08:22:27 +00:00
< / p >
< p >
The implications of this are target specific and not consistent across
all platforms.
< / p >
< p >
2019-03-02 20:34:58 +00:00
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.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-03-15 01:51:06 +00:00
{#header_open|@setAlignStack#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@setAlignStack(comptime alignment: u29){#endsyntax#}< / pre >
2018-03-15 01:51:06 +00:00
< p >
2018-09-14 15:35:03 +01:00
Ensures that a function will have a stack alignment of at least {#syntax#}alignment{#endsyntax#} bytes.
2018-03-15 01:51:06 +00:00
< / p >
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-23 03:24:07 +00:00
{#header_open|@setCold#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@setCold(is_cold: bool){#endsyntax#}< / pre >
2018-01-23 03:24:07 +00:00
< p >
Tells the optimizer that a function is rarely called.
< / p >
{#header_close#}
2017-11-07 08:22:27 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@setEvalBranchQuota#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@setEvalBranchQuota(new_quota: usize){#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
Changes the maximum number of backwards branches that compile-time code
execution can use before giving up and making a compile error.
< / p >
< p >
2018-09-14 15:35:03 +01:00
If the {#syntax#}new_quota{#endsyntax#} is smaller than the default quota ({#syntax#}1000{#endsyntax#}) or
2017-11-07 08:22:27 +00:00
a previously explicitly set quota, it is ignored.
< / p >
< p >
Example:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|evaluation exceeded 1000 backwards branches#}
test "foo" {
comptime {
var i = 0;
while (i < 1001 ) : ( i + = 1 ) { }
}
}
{#code_end#}
2018-09-14 15:35:03 +01:00
< p > Now we use {#syntax#}@setEvalBranchQuota{#endsyntax#}:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
test "foo" {
comptime {
@setEvalBranchQuota(1001);
var i = 0;
while (i < 1001 ) : ( i + = 1 ) { }
}
}
{#code_end#}
2017-11-07 08:22:27 +00:00
2018-01-17 05:22:33 +00:00
{#see_also|comptime#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@setFloatMode#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@setFloatMode(mode: @import("builtin").FloatMode){#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-09-13 20:46:34 +01:00
Sets the floating point mode of the current scope. Possible values are:
2017-11-07 08:22:27 +00:00
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
2018-11-13 13:08:37 +00:00
pub const FloatMode = enum {
2017-11-07 08:22:27 +00:00
Strict,
2018-09-13 20:46:34 +01:00
Optimized,
2018-01-19 08:03:20 +00:00
};
{#code_end#}
2017-11-07 08:22:27 +00:00
< ul >
2018-09-13 20:46:34 +01:00
< li >
2018-09-14 15:35:03 +01:00
{#syntax#}Strict{#endsyntax#} (default) - Floating point operations follow strict IEEE compliance.
2018-09-13 20:46:34 +01:00
< / li >
2017-11-07 08:22:27 +00:00
< li >
2018-09-14 15:35:03 +01:00
{#syntax#}Optimized{#endsyntax#} - Floating point operations may do all of the following:
2017-11-07 08:22:27 +00:00
< ul >
< li > Assume the arguments and result are not NaN. Optimizations are required to retain defined behavior over NaNs, but the value of the result is undefined.< / li >
< li > Assume the arguments and result are not +/-Inf. Optimizations are required to retain defined behavior over +/-Inf, but the value of the result is undefined.< / li >
< li > Treat the sign of a zero argument or result as insignificant.< / li >
< li > Use the reciprocal of an argument rather than perform division.< / li >
< li > Perform floating-point contraction (e.g. fusing a multiply followed by an addition into a fused multiply-and-add).< / li >
< li > Perform algebraically equivalent transformations that may change results in floating point (e.g. reassociate).< / li >
< / ul >
This is equivalent to < code > -ffast-math< / code > in GCC.
< / li >
< / ul >
2018-09-13 20:46:34 +01:00
< p >
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.
< / p >
2018-01-17 05:22:33 +00:00
{#see_also|Floating Point Operations#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
{#header_open|@setRuntimeSafety#}
< pre > {#syntax#}@setRuntimeSafety(safety_on: bool){#endsyntax#}< / pre >
< p >
2019-03-13 18:46:53 +00:00
Sets whether runtime safety checks are enabled for the scope that contains the function call.
2018-12-15 01:21:23 +00:00
< / p >
2019-03-13 18:46:53 +00:00
{#code_begin|test_safety|integer overflow#}
{#code_release_fast#}
test "@setRuntimeSafety" {
// The builtin applies to the scope that it is called in. So here, integer overflow
// will not be caught in ReleaseFast and ReleaseSmall modes:
// var x: u8 = 255;
// x += 1; // undefined behavior in ReleaseFast/ReleaseSmall modes.
{
// However this block has safety enabled, so safety checks happen here,
// even in ReleaseFast and ReleaseSmall modes.
@setRuntimeSafety(true);
var x: u8 = 255;
x += 1;
{
// The value can be overridden at any scope. So here integer overflow
// would not be caught in any build mode.
@setRuntimeSafety(false);
// var x: u8 = 255;
// x += 1; // undefined behavior in all build modes.
}
}
}
{#code_end#}
2019-05-01 20:09:03 +01:00
< p > Note: it is < a href = "https://github.com/ziglang/zig/issues/978" > planned< / a > to replace
{#syntax#}@setRuntimeSafety{#endsyntax#} with < code > @optimizeFor< / code > < / p >
2018-12-15 01:21:23 +00:00
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@shlExact#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@shlExact(value: T, shift_amt: Log2T) T{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
Performs the left shift operation ({#syntax#}< < {#endsyntax#}). Caller guarantees
2017-11-07 08:22:27 +00:00
that the shift will not shift any 1 bits out.
< / p >
< p >
2018-09-14 15:35:03 +01:00
The type of {#syntax#}shift_amt{#endsyntax#} is an unsigned integer with {#syntax#}log2(T.bit_count){#endsyntax#} bits.
This is because {#syntax#}shift_amt >= T.bit_count{#endsyntax#} is undefined behavior.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 05:22:33 +00:00
{#see_also|@shrExact|@shlWithOverflow#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@shlWithOverflow#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@shlWithOverflow(comptime T: type, a: T, shift_amt: Log2T, result: *T) bool{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
Performs {#syntax#}result.* = a < < b { # endsyntax # } . If overflow or underflow occurs ,
stores the overflowed bits in {#syntax#}result{#endsyntax#} and returns {#syntax#}true{#endsyntax#}.
If no overflow or underflow occurs, returns {#syntax#}false{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2018-09-14 15:35:03 +01:00
The type of {#syntax#}shift_amt{#endsyntax#} is an unsigned integer with {#syntax#}log2(T.bit_count){#endsyntax#} bits.
This is because {#syntax#}shift_amt >= T.bit_count{#endsyntax#} is undefined behavior.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 05:22:33 +00:00
{#see_also|@shlExact|@shrExact#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@shrExact#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@shrExact(value: T, shift_amt: Log2T) T{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
Performs the right shift operation ({#syntax#}>>{#endsyntax#}). Caller guarantees
2017-11-07 08:22:27 +00:00
that the shift will not shift any 1 bits out.
< / p >
< p >
2018-09-14 15:35:03 +01:00
The type of {#syntax#}shift_amt{#endsyntax#} is an unsigned integer with {#syntax#}log2(T.bit_count){#endsyntax#} bits.
This is because {#syntax#}shift_amt >= T.bit_count{#endsyntax#} is undefined behavior.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 05:22:33 +00:00
{#see_also|@shlExact|@shlWithOverflow#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 22:25:29 +01:00
2019-09-18 20:41:56 +01:00
{#header_open|@shuffle#}
2020-04-28 06:46:49 +01:00
< pre > {#syntax#}@shuffle(comptime E: type, a: std.meta.Vector(a_len, E), b: std.meta.Vector(b_len, E), comptime mask: std.meta.Vector(mask_len, i32)) std.meta.Vector(mask_len, E){#endsyntax#}< / pre >
2019-09-18 20:41:56 +01:00
< p >
Constructs a new {#link|vector|Vectors#} by selecting elements from {#syntax#}a{#endsyntax#} and
{#syntax#}b{#endsyntax#} based on {#syntax#}mask{#endsyntax#}.
< / p >
< p >
Each element in {#syntax#}mask{#endsyntax#} selects an element from either {#syntax#}a{#endsyntax#} or
{#syntax#}b{#endsyntax#}. Positive numbers select from {#syntax#}a{#endsyntax#} starting at 0.
Negative values select from {#syntax#}b{#endsyntax#}, starting at {#syntax#}-1{#endsyntax#} and going down.
It is recommended to use the {#syntax#}~{#endsyntax#} operator from indexes from {#syntax#}b{#endsyntax#}
2019-12-03 10:56:50 +00:00
so that both indexes can start from {#syntax#}0{#endsyntax#} (i.e. {#syntax#}~@as(i32, 0){#endsyntax#} is
2019-09-18 20:41:56 +01:00
{#syntax#}-1{#endsyntax#}).
< / p >
< p >
For each element of {#syntax#}mask{#endsyntax#}, if it or the selected value from
{#syntax#}a{#endsyntax#} or {#syntax#}b{#endsyntax#} is {#syntax#}undefined{#endsyntax#},
then the resulting element is {#syntax#}undefined{#endsyntax#}.
< / p >
< p >
{#syntax#}a_len{#endsyntax#} and {#syntax#}b_len{#endsyntax#} may differ in length. Out-of-bounds element
indexes in {#syntax#}mask{#endsyntax#} result in compile errors.
< / p >
< p >
If {#syntax#}a{#endsyntax#} or {#syntax#}b{#endsyntax#} is {#syntax#}undefined{#endsyntax#}, it
is equivalent to a vector of all {#syntax#}undefined{#endsyntax#} with the same length as the other vector.
If both vectors are {#syntax#}undefined{#endsyntax#}, {#syntax#}@shuffle{#endsyntax#} returns
a vector with all elements {#syntax#}undefined{#endsyntax#}.
< / p >
< p >
{#syntax#}E{#endsyntax#} must be an {#link|integer|Integers#}, {#link|float|Floats#},
{#link|pointer|Pointers#}, or {#syntax#}bool{#endsyntax#}. The mask may be any vector length, and its
length determines the result length.
< / p >
{#see_also|SIMD#}
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@sizeOf#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@sizeOf(comptime T: type) comptime_int{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
This function returns the number of bytes it takes to store {#syntax#}T{#endsyntax#} in memory.
2019-02-15 23:05:50 +00:00
The result is a target-specific compile time constant.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2019-02-15 23:05:50 +00:00
This size may contain padding bytes. If there were two consecutive T in memory, this would be the offset
in bytes between element at index 0 and the element at index 1. For {#link|integer|Integers#},
consider whether you want to use {#syntax#}@sizeOf(T){#endsyntax#} or
{#syntax#}@typeInfo(T).Int.bits{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
2019-04-25 03:31:53 +01:00
< p >
This function measures the size at runtime. For types that are disallowed at runtime, such as
{#syntax#}comptime_int{#endsyntax#} and {#syntax#}type{#endsyntax#}, the result is {#syntax#}0{#endsyntax#}.
< / p >
2020-01-16 15:12:43 +00:00
{#see_also|@bitSizeOf|@typeInfo#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 22:25:29 +01:00
2019-09-19 16:14:42 +01:00
{#header_open|@splat#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@splat(comptime len: u32, scalar: anytype) std.meta.Vector(len, @TypeOf(scalar)){#endsyntax#}< / pre >
2019-09-19 16:14:42 +01:00
< p >
Produces a vector of length {#syntax#}len{#endsyntax#} where each element is the value
{#syntax#}scalar{#endsyntax#}:
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
test "vector @splat" {
const scalar: u32 = 5;
const result = @splat(4, scalar);
2020-04-28 06:46:49 +01:00
comptime assert(@TypeOf(result) == std.meta.Vector(4, u32));
2019-12-02 02:27:55 +00:00
assert(std.mem.eql(u32, & @as([4]u32, result), & [_]u32{ 5, 5, 5, 5 }));
2019-09-19 16:14:42 +01:00
}
{#code_end#}
< p >
{#syntax#}scalar{#endsyntax#} must be an {#link|integer|Integers#}, {#link|bool|Primitive Types#},
{#link|float|Floats#}, or {#link|pointer|Pointers#}.
< / p >
{#see_also|Vectors|@shuffle#}
{#header_close#}
2020-07-01 02:52:02 +01:00
{#header_open|@src#}
< pre > {#syntax#}@src() std.builtin.SourceLocation{#endsyntax#}< / pre >
< p >
Returns a {#syntax#}SourceLocation{#endsyntax#} struct representing the function's name and location in the source code. This must be called in a function.
< / p >
{#code_begin|test#}
const std = @import("std");
const expect = std.testing.expect;
2019-09-19 16:14:42 +01:00
2020-07-01 02:52:02 +01:00
test "@src" {
doTheTest();
}
2020-06-29 01:42:37 +01:00
2020-07-01 02:52:02 +01:00
fn doTheTest() void {
const src = @src();
expect(src.line == 9);
expect(src.column == 17);
expect(std.mem.endsWith(u8, src.fn_name, "doTheTest"));
expect(std.mem.endsWith(u8, src.file, "test.zig"));
}
{#code_end#}
{#header_close#}
2018-04-15 18:21:52 +01:00
{#header_open|@sqrt#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@sqrt(value: anytype) @TypeOf(value){#endsyntax#}< / pre >
2018-04-15 18:21:52 +01:00
< p >
Performs the square root of a floating point number. Uses a dedicated hardware instruction
2020-01-02 04:27:43 +00:00
when available.
< / p >
< p >
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
< a href = "https://github.com/ziglang/zig/issues/4026" > some float operations are not yet implemented for all float types< / a > .
2018-04-15 18:21:52 +01:00
< / p >
2019-06-21 22:18:59 +01:00
{#header_close#}
{#header_open|@sin#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@sin(value: anytype) @TypeOf(value){#endsyntax#}< / pre >
2019-06-21 22:18:59 +01:00
< p >
Sine trigometric function on a floating point number. Uses a dedicated hardware instruction
2020-01-02 04:27:43 +00:00
when available.
< / p >
< p >
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
< a href = "https://github.com/ziglang/zig/issues/4026" > some float operations are not yet implemented for all float types< / a > .
2018-04-15 18:21:52 +01:00
< / p >
2019-06-21 22:18:59 +01:00
{#header_close#}
{#header_open|@cos#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@cos(value: anytype) @TypeOf(value){#endsyntax#}< / pre >
2019-06-21 22:18:59 +01:00
< p >
Cosine trigometric function on a floating point number. Uses a dedicated hardware instruction
2020-01-02 04:27:43 +00:00
when available.
< / p >
< p >
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
< a href = "https://github.com/ziglang/zig/issues/4026" > some float operations are not yet implemented for all float types< / a > .
2019-06-21 22:18:59 +01:00
< / p >
{#header_close#}
{#header_open|@exp#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@exp(value: anytype) @TypeOf(value){#endsyntax#}< / pre >
2019-06-21 22:18:59 +01:00
< p >
Base-e exponential function on a floating point number. Uses a dedicated hardware instruction
2020-01-02 04:27:43 +00:00
when available.
< / p >
< p >
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
< a href = "https://github.com/ziglang/zig/issues/4026" > some float operations are not yet implemented for all float types< / a > .
2019-06-21 22:18:59 +01:00
< / p >
{#header_close#}
{#header_open|@exp2#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@exp2(value: anytype) @TypeOf(value){#endsyntax#}< / pre >
2019-06-21 22:18:59 +01:00
< p >
Base-2 exponential function on a floating point number. Uses a dedicated hardware instruction
2020-01-02 04:27:43 +00:00
when available.
< / p >
< p >
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
< a href = "https://github.com/ziglang/zig/issues/4026" > some float operations are not yet implemented for all float types< / a > .
2019-06-21 22:18:59 +01:00
< / p >
{#header_close#}
2020-01-02 19:01:48 +00:00
{#header_open|@log#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@log(value: anytype) @TypeOf(value){#endsyntax#}< / pre >
2019-06-21 22:18:59 +01:00
< p >
Returns the natural logarithm of a floating point number. Uses a dedicated hardware instruction
2020-01-02 04:27:43 +00:00
when available.
< / p >
< p >
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
< a href = "https://github.com/ziglang/zig/issues/4026" > some float operations are not yet implemented for all float types< / a > .
2019-06-21 22:18:59 +01:00
< / p >
{#header_close#}
{#header_open|@log2#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@log2(value: anytype) @TypeOf(value){#endsyntax#}< / pre >
2019-06-21 22:18:59 +01:00
< p >
Returns the logarithm to the base 2 of a floating point number. Uses a dedicated hardware instruction
2020-01-02 04:27:43 +00:00
when available.
< / p >
< p >
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
< a href = "https://github.com/ziglang/zig/issues/4026" > some float operations are not yet implemented for all float types< / a > .
2019-06-21 22:18:59 +01:00
< / p >
{#header_close#}
{#header_open|@log10#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@log10(value: anytype) @TypeOf(value){#endsyntax#}< / pre >
2019-06-21 22:18:59 +01:00
< p >
Returns the logarithm to the base 10 of a floating point number. Uses a dedicated hardware instruction
2020-01-02 04:27:43 +00:00
when available.
< / p >
< p >
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
< a href = "https://github.com/ziglang/zig/issues/4026" > some float operations are not yet implemented for all float types< / a > .
2019-06-21 22:18:59 +01:00
< / p >
{#header_close#}
{#header_open|@fabs#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@fabs(value: anytype) @TypeOf(value){#endsyntax#}< / pre >
2019-06-21 22:18:59 +01:00
< p >
Returns the absolute value of a floating point number. Uses a dedicated hardware instruction
2020-01-02 04:27:43 +00:00
when available.
< / p >
< p >
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
< a href = "https://github.com/ziglang/zig/issues/4026" > some float operations are not yet implemented for all float types< / a > .
2019-06-21 22:18:59 +01:00
< / p >
{#header_close#}
{#header_open|@floor#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@floor(value: anytype) @TypeOf(value){#endsyntax#}< / pre >
2020-01-02 04:27:43 +00:00
< p >
Returns the largest integral value not greater than the given floating point number.
Uses a dedicated hardware instruction when available.
< / p >
2019-06-21 22:18:59 +01:00
< p >
2020-01-02 04:27:43 +00:00
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
< a href = "https://github.com/ziglang/zig/issues/4026" > some float operations are not yet implemented for all float types< / a > .
2019-06-21 22:18:59 +01:00
< / p >
{#header_close#}
{#header_open|@ceil#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@ceil(value: anytype) @TypeOf(value){#endsyntax#}< / pre >
2019-06-21 22:18:59 +01:00
< p >
2020-01-02 04:27:43 +00:00
Returns the largest integral value not less than the given floating point number.
Uses a dedicated hardware instruction when available.
< / p >
< p >
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
< a href = "https://github.com/ziglang/zig/issues/4026" > some float operations are not yet implemented for all float types< / a > .
2019-06-21 22:18:59 +01:00
< / p >
{#header_close#}
{#header_open|@trunc#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@trunc(value: anytype) @TypeOf(value){#endsyntax#}< / pre >
2020-01-02 04:27:43 +00:00
< p >
Rounds the given floating point number to an integer, towards zero.
Uses a dedicated hardware instruction when available.
< / p >
2019-06-21 22:18:59 +01:00
< p >
2020-01-02 04:27:43 +00:00
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
< a href = "https://github.com/ziglang/zig/issues/4026" > some float operations are not yet implemented for all float types< / a > .
2019-06-21 22:18:59 +01:00
< / p >
{#header_close#}
{#header_open|@round#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@round(value: anytype) @TypeOf(value){#endsyntax#}< / pre >
2018-04-15 18:21:52 +01:00
< p >
2019-06-21 22:18:59 +01:00
Rounds the given floating point number to an integer, away from zero. Uses a dedicated hardware instruction
2020-01-02 04:27:43 +00:00
when available.
< / p >
< p >
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
< a href = "https://github.com/ziglang/zig/issues/4026" > some float operations are not yet implemented for all float types< / a > .
2018-04-15 18:21:52 +01:00
< / p >
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@subWithOverflow#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@subWithOverflow(comptime T: type, a: T, b: T, result: *T) bool{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
Performs {#syntax#}result.* = a - b{#endsyntax#}. If overflow or underflow occurs,
stores the overflowed bits in {#syntax#}result{#endsyntax#} and returns {#syntax#}true{#endsyntax#}.
If no overflow or underflow occurs, returns {#syntax#}false{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-06-18 08:07:16 +01:00
{#header_open|@tagName#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@tagName(value: anytype) []const u8{#endsyntax#}< / pre >
2018-06-18 08:07:16 +01:00
< p >
2020-04-11 21:43:19 +01:00
Converts an enum value or union value to a slice of bytes representing the name.< / p > < p > If the enum is non-exhaustive and the tag value does not map to a name, it invokes safety-checked {#link|Undefined Behavior#}.
2018-06-18 08:07:16 +01:00
< / p >
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-06-18 08:07:16 +01:00
{#header_open|@TagType#}
2018-09-14 15:35:03 +01:00
< pre > {#syntax#}@TagType(T: type) type{#endsyntax#}< / pre >
2018-06-18 08:07:16 +01:00
< p >
For an enum, returns the integer type that is used to store the enumeration value.
< / p >
< p >
For a union, returns the enum type that is used to store the tag value.
< / p >
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-09-15 15:14:50 +01:00
{#header_open|@This#}
< pre > {#syntax#}@This() type{#endsyntax#}< / pre >
< p >
2020-06-20 12:16:57 +01:00
Returns the innermost struct, enum, or union that this function call is inside.
2018-09-15 15:14:50 +01:00
This can be useful for an anonymous struct that needs to refer to itself:
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
test "@This()" {
2019-06-10 00:24:24 +01:00
var items = [_]i32{ 1, 2, 3, 4 };
2018-11-13 13:08:37 +00:00
const list = List(i32){ .items = items[0..] };
2018-09-15 15:14:50 +01:00
assert(list.length() == 4);
}
fn List(comptime T: type) type {
2018-11-13 13:08:37 +00:00
return struct {
2018-09-15 15:14:50 +01:00
const Self = @This();
items: []T,
fn length(self: Self) usize {
return self.items.len;
}
};
}
{#code_end#}
< p >
When {#syntax#}@This(){#endsyntax#} is used at global scope, it returns a reference to the
2020-05-06 00:13:35 +01:00
struct that corresponds to the current file.
2018-09-15 15:14:50 +01:00
< / p >
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@truncate#}
2020-07-11 12:08:20 +01:00
< pre > {#syntax#}@truncate(comptime T: type, integer: anytype) T{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
This function truncates bits from an integer type, resulting in a smaller
2019-04-11 03:58:42 +01:00
or same-sized integer type.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2019-04-11 03:58:42 +01:00
The following produces safety-checked {#link|Undefined Behavior#}:
2017-11-07 08:22:27 +00:00
< / p >
2019-04-11 03:58:42 +01:00
{#code_begin|test_err|cast truncated bits#}
test "integer cast panic" {
var a: u16 = 0xabcd;
var b: u8 = @intCast(u8, a);
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
However this is well defined and working code:
< / p >
2019-04-11 03:58:42 +01:00
{#code_begin|test|truncate#}
const std = @import("std");
const assert = std.debug.assert;
test "integer truncation" {
var a: u16 = 0xabcd;
var b: u8 = @truncate(u8, a);
assert(b == 0xcd);
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
This function always truncates the significant bits of the integer, regardless
of endianness on the target platform.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2019-09-04 16:08:28 +01:00
{#header_open|@Type#}
< pre > {#syntax#}@Type(comptime info: @import("builtin").TypeInfo) type{#endsyntax#}< / pre >
< p >
This function is the inverse of {#link|@typeInfo#}. It reifies type information
into a {#syntax#}type{#endsyntax#}.
< / p >
< p >
It is available for the following types:
< / p >
< ul >
< li > {#syntax#}type{#endsyntax#}< / li >
< li > {#syntax#}noreturn{#endsyntax#}< / li >
< li > {#syntax#}void{#endsyntax#}< / li >
< li > {#syntax#}bool{#endsyntax#}< / li >
2019-12-05 21:38:59 +00:00
< li > {#link|Integers#} - The maximum bit count for an integer type is {#syntax#}65535{#endsyntax#}.< / li >
2019-09-04 16:08:28 +01:00
< li > {#link|Floats#}< / li >
< li > {#link|Pointers#}< / li >
< li > {#syntax#}comptime_int{#endsyntax#}< / li >
< li > {#syntax#}comptime_float{#endsyntax#}< / li >
2019-12-09 20:59:42 +00:00
< li > {#syntax#}@TypeOf(undefined){#endsyntax#}< / li >
< li > {#syntax#}@TypeOf(null){#endsyntax#}< / li >
2020-04-28 06:23:13 +01:00
< li > {#link|Arrays#}< / li >
< li > {#link|Optionals#}< / li >
2020-09-23 20:31:57 +01:00
< li > {#link|Error Set Type#}< / li >
2020-04-28 06:23:13 +01:00
< li > {#link|Error Union Type#}< / li >
< li > {#link|Vectors#}< / li >
2020-09-26 16:05:11 +01:00
< li > {#link|opaque#}< / li >
2020-09-23 20:31:57 +01:00
< li > {#link|@Frame#}< / li >
< li > {#syntax#}anyframe{#endsyntax#}< / li >
< li > {#link|struct#}< / li >
< li > {#link|enum#}< / li >
< li > {#link|Enum Literals#}< / li >
< li > {#link|union#}< / li >
2019-09-04 16:08:28 +01:00
< / ul >
< p >
2020-09-23 20:31:57 +01:00
For these types, {#syntax#}@Type{#endsyntax#} is not available:
2019-09-04 16:08:28 +01:00
< / p >
< ul >
< li > {#link|Functions#}< / li >
< li > BoundFn< / li >
< / ul >
{#header_close#}
2018-05-01 11:42:20 +01:00
{#header_open|@typeInfo#}
2019-12-16 17:07:05 +00:00
< pre > {#syntax#}@typeInfo(comptime T: type) @import("std").builtin.TypeInfo{#endsyntax#}< / pre >
2018-05-01 11:42:20 +01:00
< p >
2019-12-16 17:07:05 +00:00
Provides type reflection.
2018-05-01 11:42:20 +01:00
< / p >
2019-04-05 17:37:49 +01:00
< p >
For {#link|structs|struct#}, {#link|unions|union#}, {#link|enums|enum#}, and
{#link|error sets|Error Set Type#}, the fields are guaranteed to be in the same
order as declared. For declarations, the order is unspecified.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@typeName#}
2019-01-30 02:47:26 +00:00
< pre > {#syntax#}@typeName(T: type) [N]u8{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2019-01-30 02:47:26 +00:00
This function returns the string representation of a type, as
an array. It is equivalent to a string literal of the type name.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2019-12-09 20:59:42 +00:00
{#header_open|@TypeOf#}
2020-03-04 23:05:14 +00:00
< pre > {#syntax#}@TypeOf(...) type{#endsyntax#}< / pre >
2017-11-07 08:22:27 +00:00
< p >
2020-03-04 23:05:14 +00:00
{#syntax#}@TypeOf{#endsyntax#} is a special builtin function that takes any (nonzero) number of expressions
as parameters and returns the type of the result, using {#link|Peer Type Resolution#}.
< / p >
< p >
The expressions are evaluated, however they are guaranteed to have no < em > runtime< / em > side-effects:
2017-11-07 08:22:27 +00:00
< / p >
2019-08-31 15:38:18 +01:00
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
test "no runtime side effects" {
var data: i32 = 0;
2019-12-09 20:59:42 +00:00
const T = @TypeOf(foo(i32, &data));
2019-08-31 15:38:18 +01:00
comptime assert(T == i32);
assert(data == 0);
}
2017-11-07 08:22:27 +00:00
2019-08-31 15:38:18 +01:00
fn foo(comptime T: type, ptr: *T) T {
ptr.* += 1;
return ptr.*;
}
{#code_end#}
2019-01-31 04:36:52 +00:00
{#header_close#}
2019-07-03 18:40:40 +01:00
{#header_open|@unionInit#}
< pre > {#syntax#}@unionInit(comptime Union: type, comptime active_field_name: []const u8, init_expr) Union{#endsyntax#}< / pre >
< p >
This is the same thing as {#link|union#} initialization syntax, except that the field name is a
{#link|comptime#}-known value rather than an identifier token.
< / p >
< p >
{#syntax#}@unionInit{#endsyntax#} forwards its {#link|result location|Result Location Semantics#} to {#syntax#}init_expr{#endsyntax#}.
< / p >
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-12-15 01:21:23 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|Build Mode#}
2017-11-07 08:22:27 +00:00
< p >
2018-06-14 23:12:05 +01:00
Zig has four build modes:
2017-11-07 08:22:27 +00:00
< / p >
< ul >
2018-01-23 04:06:07 +00:00
< li > {#link|Debug#} (default)< / li >
< li > {#link|ReleaseFast#}< / li >
< li > {#link|ReleaseSafe#}< / li >
2018-06-14 23:12:05 +01:00
< li > {#link|ReleaseSmall#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< p >
To add standard build options to a < code > build.zig< / code > file:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
const Builder = @import("std").build.Builder;
2017-11-07 08:22:27 +00:00
2018-07-02 03:03:51 +01:00
pub fn build(b: *Builder) void {
2017-11-07 08:22:27 +00:00
const exe = b.addExecutable("example", "example.zig");
exe.setBuildMode(b.standardReleaseOptions());
2018-01-19 08:03:20 +00:00
b.default_step.dependOn(&exe.step);
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
This causes these options to be available:
< / p >
2018-06-14 23:12:05 +01:00
< pre > < code class = "shell" > -Drelease-safe=[bool] optimizations on and safety on
-Drelease-fast=[bool] optimizations on and safety off
-Drelease-small=[bool] size optimizations on and safety off< / code > < / pre >
2018-01-17 04:19:05 +00:00
{#header_open|Debug#}
2018-01-19 08:03:20 +00:00
< pre > < code class = "shell" > $ zig build-exe example.zig< / code > < / pre >
2017-11-07 08:22:27 +00:00
< ul >
< li > Fast compilation speed< / li >
< li > Safety checks enabled< / li >
< li > Slow runtime performance< / li >
2018-06-14 23:12:05 +01:00
< li > Large binary size< / li >
2018-09-22 15:22:01 +01:00
< li > No reproducible build requirement< / li >
2017-11-07 08:22:27 +00:00
< / ul >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|ReleaseFast#}
2020-10-19 10:18:03 +01:00
< pre > < code class = "shell" > $ zig build-exe example.zig -O ReleaseFast< / code > < / pre >
2017-11-07 08:22:27 +00:00
< ul >
< li > Fast runtime performance< / li >
< li > Safety checks disabled< / li >
< li > Slow compilation speed< / li >
2018-06-14 23:12:05 +01:00
< li > Large binary size< / li >
2018-09-22 15:22:01 +01:00
< li > Reproducible build< / li >
2017-11-07 08:22:27 +00:00
< / ul >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|ReleaseSafe#}
2020-10-19 10:18:03 +01:00
< pre > < code class = "shell" > $ zig build-exe example.zig -O ReleaseSafe< / code > < / pre >
2017-11-07 08:22:27 +00:00
< ul >
< li > Medium runtime performance< / li >
< li > Safety checks enabled< / li >
< li > Slow compilation speed< / li >
2018-06-14 23:12:05 +01:00
< li > Large binary size< / li >
2018-09-22 15:22:01 +01:00
< li > Reproducible build< / li >
2018-06-14 23:12:05 +01:00
< / ul >
{#header_close#}
{#header_open|ReleaseSmall#}
2020-10-19 10:18:03 +01:00
< pre > < code class = "shell" > $ zig build-exe example.zig -O ReleaseSmall< / code > < / pre >
2018-06-14 23:12:05 +01:00
< ul >
< li > Medium runtime performance< / li >
< li > Safety checks disabled< / li >
< li > Slow compilation speed< / li >
< li > Small binary size< / li >
2018-09-22 15:22:01 +01:00
< li > Reproducible build< / li >
2017-11-07 08:22:27 +00:00
< / ul >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-14 23:12:05 +01:00
{#see_also|Compile Variables|Zig Build System|Undefined Behavior#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2019-02-01 22:49:29 +00:00
{#header_open|Single Threaded Builds#}
2019-12-05 21:38:59 +00:00
< p > Zig has a compile option < code > --single-threaded< / code > which has the following effects:< / p >
2019-02-01 22:49:29 +00:00
< ul >
2019-04-04 17:26:47 +01:00
< li > All {#link|Thread Local Variables#} are treated as {#link|Global Variables#}.< / li >
2019-08-13 19:14:19 +01:00
< li > The overhead of {#link|Async Functions#} becomes equivalent to function call overhead.< / li >
2019-02-01 22:49:29 +00:00
< li > The {#syntax#}@import("builtin").single_threaded{#endsyntax#} becomes {#syntax#}true{#endsyntax#}
and therefore various userland APIs which read this variable become more efficient.
For example {#syntax#}std.Mutex{#endsyntax#} becomes
an empty data structure and all of its functions become no-ops.< / li >
< / ul >
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|Undefined Behavior#}
2017-11-07 08:22:27 +00:00
< p >
Zig has many instances of undefined behavior. If undefined behavior is
2018-06-18 20:01:42 +01:00
detected at compile-time, Zig emits a compile error and refuses to continue.
Most undefined behavior that cannot be detected at compile-time can be detected
at runtime. In these cases, Zig has safety checks. Safety checks can be disabled
2019-09-26 17:05:49 +01:00
on a per-block basis with {#link|@setRuntimeSafety#}. The {#link|ReleaseFast#}
and {#link|ReleaseSmall#} build modes disable all safety checks (except where overridden
by {#link|@setRuntimeSafety#}) in order to facilitate optimizations.
2017-11-07 08:22:27 +00:00
< / p >
< p >
When a safety check fails, Zig crashes with a stack trace, like this:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|reached unreachable code#}
test "safety check" {
2017-11-07 08:22:27 +00:00
unreachable;
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_open|Reaching Unreachable Code#}
2017-11-07 08:22:27 +00:00
< p > At compile-time:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|unable to evaluate constant expression#}
comptime {
2017-11-07 08:22:27 +00:00
assert(false);
}
2018-01-25 09:10:11 +00:00
fn assert(ok: bool) void {
2017-11-07 08:22:27 +00:00
if (!ok) unreachable; // assertion failure
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 20:49:49 +01:00
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
pub fn main() void {
std.debug.assert(false);
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Index out of Bounds#}
2017-11-07 08:22:27 +00:00
< p > At compile-time:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|index 5 outside array of size 5#}
comptime {
2019-11-24 07:14:21 +00:00
const array: [5]u8 = "hello".*;
2017-11-07 08:22:27 +00:00
const garbage = array[5];
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 20:49:49 +01:00
< p > At runtime:< / p >
{#code_begin|exe_err#}
pub fn main() void {
var x = foo("hello");
}
fn foo(x: []const u8) u8 {
return x[5];
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Cast Negative Number to Unsigned Integer#}
2017-11-07 08:22:27 +00:00
< p > At compile-time:< / p >
2018-11-19 00:36:27 +00:00
{#code_begin|test_err|cannot cast negative value -1 to unsigned integer type 'u32'#}
2018-01-19 08:03:20 +00:00
comptime {
2017-11-07 08:22:27 +00:00
const value: i32 = -1;
2018-06-17 07:57:07 +01:00
const unsigned = @intCast(u32, value);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 20:49:49 +01:00
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
pub fn main() void {
var value: i32 = -1;
var unsigned = @intCast(u32, value);
2020-06-19 10:38:22 +01:00
std.debug.print("value: {}\n", .{unsigned});
2018-07-02 20:49:49 +01:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-10-26 19:59:58 +01:00
To obtain the maximum value of an unsigned integer, use {#syntax#}std.math.maxInt{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Cast Truncates Data#}
2017-11-07 08:22:27 +00:00
< p > At compile-time:< / p >
2019-11-08 20:56:21 +00:00
{#code_begin|test_err|integer value 300 cannot be coerced to type 'u8'#}
2018-01-19 08:03:20 +00:00
comptime {
2017-11-07 08:22:27 +00:00
const spartan_count: u16 = 300;
2018-06-17 07:57:07 +01:00
const byte = @intCast(u8, spartan_count);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 20:49:49 +01:00
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
pub fn main() void {
var spartan_count: u16 = 300;
const byte = @intCast(u8, spartan_count);
2020-06-19 10:38:22 +01:00
std.debug.print("value: {}\n", .{byte});
2018-07-02 20:49:49 +01:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-07-02 20:49:49 +01:00
To truncate bits, use {#link|@truncate#}.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Integer Overflow#}
{#header_open|Default Operations#}
2017-11-07 08:22:27 +00:00
< p > The following operators can cause integer overflow:< / p >
< ul >
2018-09-14 15:35:03 +01:00
< li > {#syntax#}+{#endsyntax#} (addition)< / li >
< li > {#syntax#}-{#endsyntax#} (subtraction)< / li >
< li > {#syntax#}-{#endsyntax#} (negation)< / li >
< li > {#syntax#}*{#endsyntax#} (multiplication)< / li >
< li > {#syntax#}/{#endsyntax#} (division)< / li >
2018-07-02 20:49:49 +01:00
< li > {#link|@divTrunc#} (division)< / li >
< li > {#link|@divFloor#} (division)< / li >
< li > {#link|@divExact#} (division)< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< p > Example with addition at compile-time:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|operation caused overflow#}
comptime {
2017-11-07 08:22:27 +00:00
var byte: u8 = 255;
byte += 1;
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 20:49:49 +01:00
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
pub fn main() void {
var byte: u8 = 255;
byte += 1;
2020-06-19 10:38:22 +01:00
std.debug.print("value: {}\n", .{byte});
2018-07-02 20:49:49 +01:00
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Standard Library Math Functions#}
2017-11-07 08:22:27 +00:00
< p > These functions provided by the standard library return possible errors.< / p >
< ul >
2018-09-14 15:35:03 +01:00
< li > {#syntax#}@import("std").math.add{#endsyntax#}< / li >
< li > {#syntax#}@import("std").math.sub{#endsyntax#}< / li >
< li > {#syntax#}@import("std").math.mul{#endsyntax#}< / li >
< li > {#syntax#}@import("std").math.divTrunc{#endsyntax#}< / li >
< li > {#syntax#}@import("std").math.divFloor{#endsyntax#}< / li >
< li > {#syntax#}@import("std").math.divExact{#endsyntax#}< / li >
< li > {#syntax#}@import("std").math.shl{#endsyntax#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< p > Example of catching an overflow for addition:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|exe_err#}
const math = @import("std").math;
2020-06-19 10:38:22 +01:00
const print = @import("std").debug.print;
2018-02-08 08:02:41 +00:00
pub fn main() !void {
2017-11-07 08:22:27 +00:00
var byte: u8 = 255;
2018-01-19 08:03:20 +00:00
byte = if (math.add(u8, byte, 1)) |result| result else |err| {
2020-06-19 10:38:22 +01:00
print("unable to add one: {}\n", .{@errorName(err)});
2017-11-07 08:22:27 +00:00
return err;
};
2020-06-19 10:38:22 +01:00
print("result: {}\n", .{byte});
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Builtin Overflow Functions#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
These builtins return a {#syntax#}bool{#endsyntax#} of whether or not overflow
2017-11-07 08:22:27 +00:00
occurred, as well as returning the overflowed bits:
< / p >
< ul >
2018-07-02 20:49:49 +01:00
< li > {#link|@addWithOverflow#}< / li >
< li > {#link|@subWithOverflow#}< / li >
< li > {#link|@mulWithOverflow#}< / li >
< li > {#link|@shlWithOverflow#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< p >
2018-07-02 20:49:49 +01:00
Example of {#link|@addWithOverflow#}:
2017-11-07 08:22:27 +00:00
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|exe#}
2020-06-19 10:38:22 +01:00
const print = @import("std").debug.print;
2018-02-08 08:02:41 +00:00
pub fn main() void {
2017-11-07 08:22:27 +00:00
var byte: u8 = 255;
var result: u8 = undefined;
2018-01-19 08:03:20 +00:00
if (@addWithOverflow(u8, byte, 10, & result)) {
2020-06-19 10:38:22 +01:00
print("overflowed result: {}\n", .{result});
2017-11-07 08:22:27 +00:00
} else {
2020-06-19 10:38:22 +01:00
print("result: {}\n", .{result});
2017-11-07 08:22:27 +00:00
}
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Wrapping Operations#}
2017-11-07 08:22:27 +00:00
< p >
These operations have guaranteed wraparound semantics.
< / p >
< ul >
2018-09-14 15:35:03 +01:00
< li > {#syntax#}+%{#endsyntax#} (wraparound addition)< / li >
< li > {#syntax#}-%{#endsyntax#} (wraparound subtraction)< / li >
< li > {#syntax#}-%{#endsyntax#} (wraparound negation)< / li >
< li > {#syntax#}*%{#endsyntax#} (wraparound multiplication)< / li >
2017-11-07 08:22:27 +00:00
< / ul >
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
2018-10-26 19:59:58 +01:00
const std = @import("std");
const assert = std.debug.assert;
const minInt = std.math.minInt;
const maxInt = std.math.maxInt;
2017-11-07 08:22:27 +00:00
test "wraparound addition and subtraction" {
2018-10-26 19:59:58 +01:00
const x: i32 = maxInt(i32);
2017-11-07 08:22:27 +00:00
const min_val = x +% 1;
2018-10-26 19:59:58 +01:00
assert(min_val == minInt(i32));
2017-11-07 08:22:27 +00:00
const max_val = min_val -% 1;
2018-10-26 19:59:58 +01:00
assert(max_val == maxInt(i32));
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_close#}
{#header_open|Exact Left Shift Overflow#}
2017-11-07 08:22:27 +00:00
< p > At compile-time:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|operation caused overflow#}
comptime {
2019-11-08 20:56:21 +00:00
const x = @shlExact(@as(u8, 0b01010101), 2);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 20:49:49 +01:00
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
pub fn main() void {
var x: u8 = 0b01010101;
var y = @shlExact(x, 2);
2020-06-19 10:38:22 +01:00
std.debug.print("value: {}\n", .{y});
2018-07-02 20:49:49 +01:00
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Exact Right Shift Overflow#}
2017-11-07 08:22:27 +00:00
< p > At compile-time:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|exact shift shifted out 1 bits#}
comptime {
2019-11-08 20:56:21 +00:00
const x = @shrExact(@as(u8, 0b10101010), 2);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 20:49:49 +01:00
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
pub fn main() void {
var x: u8 = 0b10101010;
var y = @shrExact(x, 2);
2020-06-19 10:38:22 +01:00
std.debug.print("value: {}\n", .{y});
2018-07-02 20:49:49 +01:00
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Division by Zero#}
2017-11-07 08:22:27 +00:00
< p > At compile-time:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|division by zero#}
comptime {
2017-11-07 08:22:27 +00:00
const a: i32 = 1;
const b: i32 = 0;
const c = a / b;
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 20:49:49 +01:00
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
2017-11-07 08:22:27 +00:00
2018-07-02 20:49:49 +01:00
pub fn main() void {
var a: u32 = 1;
var b: u32 = 0;
var c = a / b;
2020-06-19 10:38:22 +01:00
std.debug.print("value: {}\n", .{c});
2018-07-02 20:49:49 +01:00
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Remainder Division by Zero#}
2017-11-07 08:22:27 +00:00
< p > At compile-time:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|division by zero#}
comptime {
2017-11-07 08:22:27 +00:00
const a: i32 = 10;
const b: i32 = 0;
const c = a % b;
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 20:49:49 +01:00
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
2017-11-07 08:22:27 +00:00
2018-07-02 20:49:49 +01:00
pub fn main() void {
var a: u32 = 10;
var b: u32 = 0;
var c = a % b;
2020-06-19 10:38:22 +01:00
std.debug.print("value: {}\n", .{c});
2018-07-02 20:49:49 +01:00
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Exact Division Remainder#}
2018-07-02 20:49:49 +01:00
< p > At compile-time:< / p >
{#code_begin|test_err|exact division had a remainder#}
comptime {
const a: u32 = 10;
const b: u32 = 3;
const c = @divExact(a, b);
}
{#code_end#}
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
pub fn main() void {
var a: u32 = 10;
var b: u32 = 3;
var c = @divExact(a, b);
2020-06-19 10:38:22 +01:00
std.debug.print("value: {}\n", .{c});
2018-07-02 20:49:49 +01:00
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Attempt to Unwrap Null#}
2017-11-07 08:22:27 +00:00
< p > At compile-time:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|unable to unwrap null#}
comptime {
2018-06-10 04:42:14 +01:00
const optional_number: ?i32 = null;
const number = optional_number.?;
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 20:49:49 +01:00
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
pub fn main() void {
var optional_number: ?i32 = null;
var number = optional_number.?;
2020-06-19 10:38:22 +01:00
std.debug.print("value: {}\n", .{number});
2018-07-02 20:49:49 +01:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p > One way to avoid this crash is to test for null instead of assuming non-null, with
2018-09-14 15:35:03 +01:00
the {#syntax#}if{#endsyntax#} expression:< / p >
2018-01-17 08:24:03 +00:00
{#code_begin|exe|test#}
2020-06-19 10:38:22 +01:00
const print = @import("std").debug.print;
2018-01-25 09:10:11 +00:00
pub fn main() void {
2018-06-10 04:42:14 +01:00
const optional_number: ?i32 = null;
2017-11-07 08:22:27 +00:00
2018-06-10 04:42:14 +01:00
if (optional_number) |number| {
2020-06-19 10:38:22 +01:00
print("got number: {}\n", .{number});
2017-11-07 08:22:27 +00:00
} else {
2020-06-19 10:38:22 +01:00
print("it's null\n", .{});
2017-11-07 08:22:27 +00:00
}
2018-01-17 08:24:03 +00:00
}
{#code_end#}
2018-07-02 20:49:49 +01:00
{#see_also|Optionals#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Attempt to Unwrap Error#}
2017-11-07 08:22:27 +00:00
< p > At compile-time:< / p >
2018-02-08 08:02:41 +00:00
{#code_begin|test_err|caught unexpected error 'UnableToReturnNumber'#}
2018-01-19 08:03:20 +00:00
comptime {
const number = getNumberOrFail() catch unreachable;
2017-11-07 08:22:27 +00:00
}
2018-02-08 08:02:41 +00:00
fn getNumberOrFail() !i32 {
2017-11-07 08:22:27 +00:00
return error.UnableToReturnNumber;
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 20:49:49 +01:00
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
pub fn main() void {
const number = getNumberOrFail() catch unreachable;
2020-06-19 10:38:22 +01:00
std.debug.print("value: {}\n", .{number});
2018-07-02 20:49:49 +01:00
}
fn getNumberOrFail() !i32 {
return error.UnableToReturnNumber;
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p > One way to avoid this crash is to test for an error instead of assuming a successful result, with
2018-09-14 15:35:03 +01:00
the {#syntax#}if{#endsyntax#} expression:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|exe#}
2020-06-19 10:38:22 +01:00
const print = @import("std").debug.print;
2017-11-07 08:22:27 +00:00
2018-01-25 09:10:11 +00:00
pub fn main() void {
2017-11-07 08:22:27 +00:00
const result = getNumberOrFail();
if (result) |number| {
2020-06-19 10:38:22 +01:00
print("got number: {}\n", .{number});
2017-11-07 08:22:27 +00:00
} else |err| {
2020-06-19 10:38:22 +01:00
print("got error: {}\n", .{@errorName(err)});
2017-11-07 08:22:27 +00:00
}
}
2018-02-08 08:02:41 +00:00
fn getNumberOrFail() !i32 {
2017-11-07 08:22:27 +00:00
return error.UnableToReturnNumber;
2018-01-17 08:24:03 +00:00
}
{#code_end#}
2018-07-02 20:49:49 +01:00
{#see_also|Errors#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Invalid Error Code#}
2017-11-07 08:22:27 +00:00
< p > At compile-time:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|integer value 11 represents no error#}
2017-11-07 08:22:27 +00:00
comptime {
const err = error.AnError;
2018-06-18 23:48:29 +01:00
const number = @errorToInt(err) + 10;
const invalid_err = @intToError(number);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 20:49:49 +01:00
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
pub fn main() void {
var err = error.AnError;
var number = @errorToInt(err) + 500;
var invalid_err = @intToError(number);
2020-06-19 10:38:22 +01:00
std.debug.print("value: {}\n", .{number});
2018-07-02 20:49:49 +01:00
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Invalid Enum Cast#}
2018-07-02 20:49:49 +01:00
< p > At compile-time:< / p >
{#code_begin|test_err|has no tag matching integer value 3#}
2018-11-13 13:08:37 +00:00
const Foo = enum {
2020-10-14 16:34:05 +01:00
a,
b,
c,
2018-07-02 20:49:49 +01:00
};
comptime {
const a: u2 = 3;
const b = @intToEnum(Foo, a);
}
{#code_end#}
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
2018-11-13 13:08:37 +00:00
const Foo = enum {
2020-10-14 16:34:05 +01:00
a,
b,
c,
2018-07-02 20:49:49 +01:00
};
2017-11-07 08:22:27 +00:00
2018-07-02 20:49:49 +01:00
pub fn main() void {
var a: u2 = 3;
var b = @intToEnum(Foo, a);
2020-06-19 10:38:22 +01:00
std.debug.print("value: {}\n", .{@tagName(b)});
2018-07-02 20:49:49 +01:00
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 20:01:42 +01:00
{#header_open|Invalid Error Set Cast#}
2018-07-09 16:13:29 +01:00
< p > At compile-time:< / p >
{#code_begin|test_err|error.B not a member of error set 'Set2'#}
2018-11-13 13:08:37 +00:00
const Set1 = error{
2018-07-09 16:13:29 +01:00
A,
B,
};
2018-11-13 13:08:37 +00:00
const Set2 = error{
2018-07-09 16:13:29 +01:00
A,
C,
};
comptime {
_ = @errSetCast(Set2, Set1.B);
}
{#code_end#}
< p > At runtime:< / p >
{#code_begin|exe_err#}
2018-07-10 15:37:58 +01:00
const std = @import("std");
2018-11-13 13:08:37 +00:00
const Set1 = error{
2018-07-09 16:13:29 +01:00
A,
B,
};
2018-11-13 13:08:37 +00:00
const Set2 = error{
2018-07-09 16:13:29 +01:00
A,
C,
};
pub fn main() void {
2018-07-10 15:37:58 +01:00
foo(Set1.B);
2018-07-09 16:13:29 +01:00
}
2018-07-10 15:37:58 +01:00
fn foo(set1: Set1) void {
const x = @errSetCast(Set2, set1);
2020-06-19 10:38:22 +01:00
std.debug.print("value: {}\n", .{x});
2018-07-09 16:13:29 +01:00
}
{#code_end#}
2018-06-18 20:01:42 +01:00
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|Incorrect Pointer Alignment#}
2018-07-09 16:13:29 +01:00
< p > At compile-time:< / p >
{#code_begin|test_err|pointer address 0x1 is not aligned to 4 bytes#}
comptime {
2019-12-15 11:48:35 +00:00
const ptr = @intToPtr(*align(1) i32, 0x1);
2018-07-09 16:13:29 +01:00
const aligned = @alignCast(4, ptr);
}
{#code_end#}
< p > At runtime:< / p >
{#code_begin|exe_err#}
2020-02-23 17:03:50 +00:00
const mem = @import("std").mem;
2018-07-09 16:13:29 +01:00
pub fn main() !void {
2019-06-10 00:24:24 +01:00
var array align(4) = [_]u32{ 0x11111111, 0x11111111 };
2020-02-23 17:03:50 +00:00
const bytes = mem.sliceAsBytes(array[0..]);
2018-07-09 16:13:29 +01:00
if (foo(bytes) != 0x11111111) return error.Wrong;
}
fn foo(bytes: []u8) u32 {
const slice4 = bytes[1..5];
2020-02-23 17:03:50 +00:00
const int_slice = mem.bytesAsSlice(u32, @alignCast(4, slice4));
2018-07-09 16:13:29 +01:00
return int_slice[0];
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Wrong Union Field Access#}
2018-07-10 15:37:58 +01:00
< p > At compile-time:< / p >
{#code_begin|test_err|accessing union field 'float' while field 'int' is set#}
comptime {
2018-11-13 13:08:37 +00:00
var f = Foo{ .int = 42 };
2018-07-10 15:37:58 +01:00
f.float = 12.34;
}
2018-11-13 13:08:37 +00:00
const Foo = union {
2018-07-10 15:37:58 +01:00
float: f32,
int: u32,
};
{#code_end#}
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
2018-11-13 13:08:37 +00:00
const Foo = union {
2018-07-10 15:37:58 +01:00
float: f32,
int: u32,
};
pub fn main() void {
2018-11-13 13:08:37 +00:00
var f = Foo{ .int = 42 };
2018-07-10 15:37:58 +01:00
bar(&f);
}
fn bar(f: *Foo) void {
f.float = 12.34;
2020-06-19 10:38:22 +01:00
std.debug.print("value: {}\n", .{f.float});
2018-07-10 15:37:58 +01:00
}
{#code_end#}
< p >
2018-09-14 15:35:03 +01:00
This safety is not available for {#syntax#}extern{#endsyntax#} or {#syntax#}packed{#endsyntax#} unions.
2018-07-10 15:37:58 +01:00
< / p >
< p >
To change the active field of a union, assign the entire union, like this:
< / p >
{#code_begin|exe#}
const std = @import("std");
2018-11-13 13:08:37 +00:00
const Foo = union {
2018-07-10 15:37:58 +01:00
float: f32,
int: u32,
};
pub fn main() void {
2018-11-13 13:08:37 +00:00
var f = Foo{ .int = 42 };
2018-07-10 15:37:58 +01:00
bar(&f);
}
fn bar(f: *Foo) void {
2018-11-13 13:08:37 +00:00
f.* = Foo{ .float = 12.34 };
2020-06-19 10:38:22 +01:00
std.debug.print("value: {}\n", .{f.float});
2018-07-10 15:37:58 +01:00
}
{#code_end#}
< p >
To change the active field of a union when a meaningful value for the field is not known,
use {#link|undefined#}, like this:
< / p >
{#code_begin|exe#}
const std = @import("std");
2018-11-13 13:08:37 +00:00
const Foo = union {
2018-07-10 15:37:58 +01:00
float: f32,
int: u32,
};
pub fn main() void {
2018-11-13 13:08:37 +00:00
var f = Foo{ .int = 42 };
f = Foo{ .float = undefined };
2018-07-10 15:37:58 +01:00
bar(&f);
2020-06-19 10:38:22 +01:00
std.debug.print("value: {}\n", .{f.float});
2018-07-10 15:37:58 +01:00
}
fn bar(f: *Foo) void {
f.float = 12.34;
}
{#code_end#}
2019-02-27 03:46:35 +00:00
{#see_also|union|extern union#}
2018-06-19 21:06:10 +01:00
{#header_close#}
2017-11-17 03:13:20 +00:00
2019-02-14 23:59:20 +00:00
{#header_open|Out of Bounds Float to Integer Cast#}
2018-06-19 21:06:10 +01:00
< p > TODO< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 20:01:42 +01:00
2019-02-14 23:59:20 +00:00
{#header_open|Pointer Cast Invalid Null#}
2019-03-25 16:55:45 +00:00
< p >
This happens when casting a pointer with the address 0 to a pointer which may not have the address 0.
For example, {#link|C Pointers#}, {#link|Optional Pointers#}, and {#link|allowzero#} pointers
allow address zero, but normal {#link|Pointers#} do not.
< / p >
2019-02-14 23:59:20 +00:00
< p > At compile-time:< / p >
{#code_begin|test_err|null pointer casted to type#}
comptime {
const opt_ptr: ?*i32 = null;
const ptr = @ptrCast(*i32, opt_ptr);
}
{#code_end#}
< p > At runtime:< / p >
{#code_begin|exe_err#}
pub fn main() void {
var opt_ptr: ?*i32 = null;
var ptr = @ptrCast(*i32, opt_ptr);
}
{#code_end#}
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Memory#}
2019-03-19 01:40:24 +00:00
< p >
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:
< / p >
< p > {#link|Where are the bytes?#}< / p >
< p >
Like Zig, the C programming language has manual memory management. However, unlike Zig,
C has a default allocator - < code > malloc< / code > , < code > realloc< / code > , and < code > free< / code > .
When linking against libc, Zig exposes this allocator with {#syntax#}std.heap.c_allocator{#endsyntax#}.
However, by convention, there is no default allocator in Zig. Instead, functions which need to
allocate accept an {#syntax#}*Allocator{#endsyntax#} parameter. Likewise, data structures such as
{#syntax#}std.ArrayList{#endsyntax#} accept an {#syntax#}*Allocator{#endsyntax#} parameter in
their initialization functions:
< / p >
{#code_begin|test|allocator#}
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
test "using an allocator" {
var buffer: [100]u8 = undefined;
const allocator = &std.heap.FixedBufferAllocator.init(&buffer).allocator;
const result = try concat(allocator, "foo", "bar");
assert(std.mem.eql(u8, "foobar", result));
}
fn concat(allocator: *Allocator, a: []const u8, b: []const u8) ![]u8 {
const result = try allocator.alloc(u8, a.len + b.len);
std.mem.copy(u8, result, a);
std.mem.copy(u8, result[a.len..], b);
return result;
}
{#code_end#}
< p >
In the above example, 100 bytes of stack memory are used to initialize a
{#syntax#}FixedBufferAllocator{#endsyntax#}, which is then passed to a function.
As a convenience there is a global {#syntax#}FixedBufferAllocator{#endsyntax#}
2020-01-30 03:39:08 +00:00
available for quick tests at {#syntax#}std.testing.allocator{#endsyntax#},
which will also do perform basic leak detection.
2019-03-19 01:40:24 +00:00
< / p >
< p >
2020-08-12 09:56:34 +01:00
Zig has a general purpose allocator available to be imported
with {#syntax#}std.heap.GeneralPurposeAllocator{#endsyntax#}. However, it is still recommended to
2019-03-19 01:40:24 +00:00
follow the {#link|Choosing an Allocator#} guide.
< / p >
{#header_open|Choosing an Allocator#}
< p > What allocator to use depends on a number of factors. Here is a flow chart to help you decide:
< / p >
< ol >
< li >
Are you making a library? In this case, best to accept an {#syntax#}*Allocator{#endsyntax#}
as a parameter and allow your library's users to decide what allocator to use.
< / li >
< li > Are you linking libc? In this case, {#syntax#}std.heap.c_allocator{#endsyntax#} is likely
the right choice, at least for your main allocator.< / li >
< li >
Is the maximum number of bytes that you will need bounded by a number known at
{#link|comptime#}? In this case, use {#syntax#}std.heap.FixedBufferAllocator{#endsyntax#} or
{#syntax#}std.heap.ThreadSafeFixedBufferAllocator{#endsyntax#} depending on whether you need
thread-safety or not.
< / li >
< li >
Is your program a command line application which runs from start to end without any fundamental
cyclical pattern (such as a video game main loop, or a web server request handler),
such that it would make sense to free everything at once at the end?
In this case, it is recommended to follow this pattern:
{#code_begin|exe|cli_allocation#}
const std = @import("std");
pub fn main() !void {
2019-11-25 22:25:06 +00:00
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
2019-03-19 01:40:24 +00:00
defer arena.deinit();
const allocator = &arena.allocator;
const ptr = try allocator.create(i32);
2020-06-19 10:38:22 +01:00
std.debug.print("ptr={*}\n", .{ptr});
2019-03-19 01:40:24 +00:00
}
{#code_end#}
When using this kind of allocator, there is no need to free anything manually. Everything
gets freed at once with the call to {#syntax#}arena.deinit(){#endsyntax#}.
< / li >
< li >
Are the allocations part of a cyclical pattern such as a video game main loop, or a web
server request handler? If the allocations can all be freed at once, at the end of the cycle,
for example once the video game frame has been fully rendered, or the web server request has
been served, then {#syntax#}std.heap.ArenaAllocator{#endsyntax#} is a great candidate. As
demonstrated in the previous bullet point, this allows you to free entire arenas at once.
Note also that if an upper bound of memory can be established, then
{#syntax#}std.heap.FixedBufferAllocator{#endsyntax#} can be used as a further optimization.
< / li >
< li >
Are you writing a test, and you want to make sure {#syntax#}error.OutOfMemory{#endsyntax#}
2020-01-30 03:39:08 +00:00
is handled correctly? In this case, use {#syntax#}std.testing.FailingAllocator{#endsyntax#}.
2019-03-19 01:40:24 +00:00
< / li >
< li >
2020-08-08 10:15:34 +01:00
Are you writing a test? In this case, use {#syntax#}std.testing.allocator{#endsyntax#}.
< / li >
< li >
Finally, if none of the above apply, you need a general purpose allocator.
Zig's general purpose allocator is available as a function that takes a {#link|comptime#}
{#link|struct#} of configuration options and returns a type.
2020-08-08 10:15:46 +01:00
Generally, you will set up one {#syntax#}std.heap.GeneralPurposeAllocator{#endsyntax#} in
2020-08-08 10:15:34 +01:00
your main function, and then pass it or sub-allocators around to various parts of your
application.
< / li >
< li >
2019-03-19 01:40:24 +00:00
You can also consider {#link|Implementing an Allocator#}.
< / li >
< / ol >
{#header_close#}
{#header_open|Where are the bytes?#}
< p > String literals such as {#syntax#}"foo"{#endsyntax#} are in the global constant data section.
This is why it is an error to pass a string literal to a mutable slice, like this:
< / p >
{#code_begin|test_err|expected type '[]u8'#}
fn foo(s: []u8) void {}
test "string literal to mutable slice" {
foo("hello");
}
{#code_end#}
< p > However if you make the slice constant, then it works:< / p >
{#code_begin|test|strlit#}
fn foo(s: []const u8) void {}
test "string literal to constant slice" {
foo("hello");
}
{#code_end#}
< p >
Just like string literals, `const` declarations, when the value is known at {#link|comptime#},
are stored in the global constant data section. Also {#link|Compile Time Variables#} are stored
in the global constant data section.
< / p >
< p >
`var` declarations inside functions are stored in the function's stack frame. Once a function returns,
any {#link|Pointers#} to variables in the function's stack frame become invalid references, and
dereferencing them becomes unchecked {#link|Undefined Behavior#}.
< / p >
< p >
`var` declarations at the top level or in {#link|struct#} declarations are stored in the global
data section.
< / p >
< p >
The location of memory allocated with {#syntax#}allocator.alloc{#endsyntax#} or
{#syntax#}allocator.create{#endsyntax#} is determined by the allocator's implementation.
< / p >
2019-12-05 21:38:59 +00:00
< p > TODO: thread local variables< / p >
2019-03-19 01:40:24 +00:00
{#header_close#}
{#header_open|Implementing an Allocator#}
< p > Zig programmers can implement their own allocators by fulfilling the Allocator interface.
In order to do this one must read carefully the documentation comments in std/mem.zig and
then supply a {#syntax#}reallocFn{#endsyntax#} and a {#syntax#}shrinkFn{#endsyntax#}.
< / p >
< p >
There are many example allocators to look at for inspiration. Look at std/heap.zig and
at this
< a href = "https://github.com/andrewrk/zig-general-purpose-allocator/" > work-in-progress general purpose allocator< / a > .
TODO: once < a href = "https://github.com/ziglang/zig/issues/21" > #21< / a > is done, link to the docs
here.
< / p >
{#header_close#}
{#header_open|Heap Allocation Failure#}
< p >
Many programming languages choose to handle the possibility of heap allocation failure by
unconditionally crashing. By convention, Zig programmers do not consider this to be a
satisfactory solution. Instead, {#syntax#}error.OutOfMemory{#endsyntax#} represents
heap allocation failure, and Zig libraries return this error code whenever heap allocation
failure prevented an operation from completing successfully.
< / p >
< p >
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:
< / p >
< ul >
< li > Only some operating systems have an overcommit feature.
< ul >
< li > Linux has it enabled by default, but it is configurable.< / li >
< li > Windows does not overcommit.< / li >
< li > Embedded systems do not have overcommit.< / li >
< li > Hobby operating systems may or may not have overcommit.< / li >
< / ul >
< / li >
< li >
For real-time systems, not only is there no overcommit, but typically the maximum amount
of memory per application is determined ahead of time.
< / li >
< li >
When writing a library, one of the main goals is code reuse. By making code handle
allocation failure correctly, a library becomes eligible to be reused in
more contexts.
< / li >
< li >
Although some software has grown to depend on overcommit being enabled, its existence
is the source of countless user experience disasters. When a system with overcommit enabled,
such as Linux on default settings, comes close to memory exhaustion, the system locks up
and becomes unusable. At this point, the OOM Killer selects an application to kill
based on heuristics. This non-deterministic decision often results in an important process
being killed, and often fails to return the system back to working order.
< / li >
< / ul >
{#header_close#}
{#header_open|Recursion#}
< p >
Recursion is a fundamental tool in modeling software. However it has an often-overlooked problem:
unbounded memory allocation.
< / p >
< p >
Recursion is an area of active experimentation in Zig and so the documentation here is not final.
You can read a
< a href = "https://ziglang.org/download/0.3.0/release-notes.html#recursion" > summary of recursion status in the 0.3.0 release notes< / a > .
< / p >
< p >
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.
< / p >
{#header_close#}
{#header_open|Lifetime and Ownership#}
< p >
It is the Zig programmer's responsibility to ensure that a {#link|pointer|Pointers#} is not
accessed when the memory pointed to is no longer available. Note that a {#link|slice|Slices#}
is a form of pointer, in that it references other memory.
< / p >
< p >
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.
< / p >
< p >
For example, the function's documentation may say "caller owns the returned memory", in which case
the code that calls the function must have a plan for when to free that memory. Probably in this situation,
the function will accept an {#syntax#}*Allocator{#endsyntax#} parameter.
< / p >
< p >
2020-06-12 16:58:43 +01:00
Sometimes the lifetime of a pointer may be more complicated. For example, the
{#syntax#}std.ArrayList(T).items{#endsyntax#} slice has a lifetime that remains
2019-03-19 01:40:24 +00:00
valid until the next time the list is resized, such as by appending new elements.
< / p >
< p >
The API documentation for functions and data structures should take great care to explain
the ownership and lifetime semantics of pointers. Ownership determines whose responsibility it
is to free the memory referenced by the pointer, and lifetime determines the point at which
the memory becomes inaccessible (lest {#link|Undefined Behavior#} occur).
< / p >
{#header_close#}
2017-11-07 08:22:27 +00:00
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Compile Variables#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
Compile variables are accessible by importing the {#syntax#}"builtin"{#endsyntax#} package,
2017-11-07 08:22:27 +00:00
which the compiler makes available to every Zig source file. It contains
compile-time constants such as the current target, endianness, and release mode.
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
const builtin = @import("builtin");
const separator = if (builtin.os == builtin.Os.windows) '\\' else '/';
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
Example of what is imported with {#syntax#}@import("builtin"){#endsyntax#}:
2017-11-07 08:22:27 +00:00
< / p >
2018-06-08 00:10:45 +01:00
{#builtin#}
2018-01-17 05:22:33 +00:00
{#see_also|Build Mode#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Root Source File#}
2017-11-07 08:22:27 +00:00
< p > TODO: explain how root source file finds other files< / p >
< p > TODO: pub fn main< / p >
< p > TODO: pub fn panic< / p >
< p > TODO: if linking with libc you can use export fn main< / p >
< p > TODO: order independent top level declarations< / p >
< p > TODO: lazy analysis< / p >
< p > TODO: using comptime { _ = @import() }< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Zig Test#}
2019-03-21 03:49:35 +00:00
< p >
< code > zig test< / code > is a tool that can be used to quickly build and run Zig code
to make sure behavior meets expectations. {#syntax#}@import("builtin").is_test{#endsyntax#}
is available for code to detect whether the current build is a test build.
< / p >
{#code_begin|test|detect_test#}
const std = @import("std");
2020-02-27 19:41:44 +00:00
const builtin = std.builtin;
2019-03-21 03:49:35 +00:00
const assert = std.debug.assert;
test "builtin.is_test" {
assert(builtin.is_test);
}
{#code_end#}
< p >
Zig has lazy top level declaration analysis, which means that if a function is not called,
or otherwise used, it is not analyzed. This means that there may be an undiscovered
compile error in a function because it is never called.
< / p >
{#code_begin|test|unused_fn#}
fn unused() i32 {
return "wrong return type";
}
test "unused function" { }
{#code_end#}
< p >
Note that, while in {#link|Debug#} and {#link|ReleaseSafe#} modes, {#link|unreachable#} emits a
call to {#link|@panic#}, in {#link|ReleaseFast#} and {#link|ReleaseSmall#} modes, it is really
undefined behavior. The implementation of {#syntax#}std.debug.assert{#endsyntax#} is as
simple as:
< / p >
{#code_begin|syntax#}
pub fn assert(ok: bool) void {
if (!ok) unreachable;
}
{#code_end#}
< p >
This means that when testing in ReleaseFast or ReleaseSmall mode, {#syntax#}assert{#endsyntax#}
is not sufficient to check the result of a computation:
< / p >
2019-07-20 18:59:18 +01:00
{#code_begin|syntax#}
2019-03-21 03:49:35 +00:00
const std = @import("std");
const assert = std.debug.assert;
test "assert in release fast mode" {
assert(false);
}
{#code_end#}
2019-07-20 18:59:18 +01:00
< p >
When compiling this test in {#link|ReleaseFast#} mode, it invokes unchecked
{#link|Undefined Behavior#}. Since that could do anything, this documentation
cannot show you the output.
< / p >
2019-03-21 03:49:35 +00:00
< p >
Better practice for checking the output when testing is to use {#syntax#}std.testing.expect{#endsyntax#}:
< / p >
{#code_begin|test_err|test failure#}
{#code_release_fast#}
const std = @import("std");
const expect = std.testing.expect;
test "assert in release fast mode" {
expect(false);
}
{#code_end#}
< p > See the rest of the {#syntax#}std.testing{#endsyntax#} namespace for more available functions.< / p >
< p >
< code > zig test< / code > has a few command line parameters which affect the compilation. See
< code > zig --help< / code > for a full list. The most interesting one is < code > --test-filter [text]< / code > .
This makes the test build only include tests whose name contains the supplied filter text.
Again, thanks to lazy analysis, this can allow you to narrow a build to only a few functions in
isolation.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2020-07-05 23:37:44 +01:00
2020-10-17 05:29:33 +01:00
{#header_open|Zig Build System#}
< p >
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.
< / p >
< p >
Some examples of tasks the build system can help with:
< / p >
< ul >
< li > Creating build artifacts by executing the Zig compiler. This includes
building Zig source code as well as C and C++ source code.< / li >
< li > Capturing user-configured options and using those options to configure
the build.< / li >
< li > Surfacing build configuration as {#link|comptime#} values by providing a
file that can be {#link|imported|@import#} by Zig code.< / li >
< li > Caching build artifacts to avoid unnecessarily repeating steps.< / li >
< li > Executing build artifacts or system-installed tools.< / li >
< li > Running tests and verifying the output of executing a build artifact matches
the expected value.< / li >
< li > Running < code > zig fmt< / code > on a codebase or a subset of it.< / li >
< li > Custom tasks.< / li >
< / ul >
< p >
To use the build system, run < code class = "shell" > zig build --help< / code >
to see a command-line usage help menu. This will include project-specific
options that were declared in the build.zig script.
< / p >
2020-07-05 23:37:44 +01:00
2020-10-17 05:29:33 +01:00
{#header_open|Building an Executable#}
2020-07-05 23:37:44 +01:00
< p > This < code > build.zig< / code > file is automatically generated
by < code > zig init-exe< / code > .< / p >
{#code_begin|syntax|build#}
const Builder = @import("std").build.Builder;
pub fn build(b: *Builder) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
const mode = b.standardReleaseOptions();
2020-10-17 05:29:33 +01:00
const exe = b.addExecutable("example", "src/main.zig");
2020-07-05 23:37:44 +01:00
exe.setTarget(target);
exe.setBuildMode(mode);
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
2020-10-17 05:29:33 +01:00
if (b.args) |args| {
run_cmd.addArgs(args);
}
2020-07-05 23:37:44 +01:00
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
}
{#code_end#}
{#header_close#}
2020-10-17 05:29:33 +01:00
{#header_open|Building a Library#}
< p > This < code > build.zig< / code > file is automatically generated
by < code > zig init-lib< / code > .< / p >
{#code_begin|syntax|build#}
2020-07-05 23:37:44 +01:00
const Builder = @import("std").build.Builder;
pub fn build(b: *Builder) void {
const mode = b.standardReleaseOptions();
2020-10-17 05:29:33 +01:00
const lib = b.addStaticLibrary("example", "src/main.zig");
2020-07-05 23:37:44 +01:00
lib.setBuildMode(mode);
2020-10-17 05:29:33 +01:00
lib.install();
2020-07-05 23:37:44 +01:00
var main_tests = b.addTest("src/main.zig");
main_tests.setBuildMode(mode);
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&main_tests.step);
}
2020-10-17 05:29:33 +01:00
{#code_end#}
{#header_close#}
{#header_open|Compiling C Source Code#}
< pre > {#syntax#}
lib.addCSourceFile("src/lib.c", & [_][]const u8{
"-Wall",
"-Wextra",
"-Werror",
});
{#endsyntax#}< / pre >
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|C#}
2017-11-07 08:22:27 +00:00
< p >
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.
< / p >
< p >
There are a few ways that Zig facilitates C interop.
< / p >
2018-01-17 04:19:05 +00:00
{#header_open|C Type Primitives#}
2017-11-07 08:22:27 +00:00
< p >
These have guaranteed C ABI compatibility and can be used like any other type.
< / p >
< ul >
2018-09-14 15:35:03 +01:00
< li > {#syntax#}c_short{#endsyntax#}< / li >
< li > {#syntax#}c_ushort{#endsyntax#}< / li >
< li > {#syntax#}c_int{#endsyntax#}< / li >
< li > {#syntax#}c_uint{#endsyntax#}< / li >
< li > {#syntax#}c_long{#endsyntax#}< / li >
< li > {#syntax#}c_ulong{#endsyntax#}< / li >
< li > {#syntax#}c_longlong{#endsyntax#}< / li >
< li > {#syntax#}c_ulonglong{#endsyntax#}< / li >
< li > {#syntax#}c_longdouble{#endsyntax#}< / li >
< li > {#syntax#}c_void{#endsyntax#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
2018-01-17 05:22:33 +00:00
{#see_also|Primitive Types#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2019-02-14 23:59:20 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|Import from C Header File#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
The {#syntax#}@cImport{#endsyntax#} builtin function can be used
2017-11-07 08:22:27 +00:00
to directly import symbols from .h files:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|exe#}
{#link_libc#}
2018-01-20 03:17:31 +00:00
const c = @cImport({
2018-05-25 02:27:44 +01:00
// See https://github.com/ziglang/zig/issues/515
2018-01-20 03:17:31 +00:00
@cDefine("_NO_CRT_STDIO_INLINE", "1");
@cInclude("stdio.h");
});
2018-01-25 09:10:11 +00:00
pub fn main() void {
2019-11-24 07:14:21 +00:00
_ = c.printf("hello\n");
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
The {#syntax#}@cImport{#endsyntax#} function takes an expression as a parameter.
2017-11-07 08:22:27 +00:00
This expression is evaluated at compile-time and is used to control
preprocessor directives and include multiple .h files:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
const builtin = @import("builtin");
2017-11-07 08:22:27 +00:00
const c = @cImport({
2020-03-23 23:00:52 +00:00
@cDefine("NDEBUG", builtin.mode == .ReleaseFast);
2017-11-07 08:22:27 +00:00
if (something) {
@cDefine("_GNU_SOURCE", {});
}
2018-01-19 08:03:20 +00:00
@cInclude("stdlib.h");
2017-11-07 08:22:27 +00:00
if (something) {
@cUndef("_GNU_SOURCE");
}
@cInclude("soundio.h");
2018-01-19 08:03:20 +00:00
});
{#code_end#}
2018-01-17 05:22:33 +00:00
{#see_also|@cImport|@cInclude|@cDefine|@cUndef|@import#}
2018-08-27 22:44:58 +01:00
{#header_close#}
2019-02-14 23:59:20 +00:00
{#header_open|C Pointers#}
< p >
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.
< / p >
< p >
When importing C header files, it is ambiguous whether pointers should be translated as
single-item pointers ({#syntax#}*T{#endsyntax#}) or unknown-length pointers ({#syntax#}[*]T{#endsyntax#}).
C pointers are a compromise so that Zig code can utilize translated header files directly.
< / p >
< p > {#syntax#}[*c]T{#endsyntax#} - C pointer.< / p >
< ul >
< li > Supports all the syntax of the other two pointer types.< / li >
2019-11-08 20:56:21 +00:00
< li > Coerces to other pointer types, as well as {#link|Optional Pointers#}.
When a C pointer is coerced to a non-optional pointer, safety-checked
2019-02-14 23:59:20 +00:00
{#link|Undefined Behavior#} occurs if the address is 0.
< / li >
< li > Allows address 0. On non-freestanding targets, dereferencing address 0 is safety-checked
2019-02-22 15:56:49 +00:00
{#link|Undefined Behavior#}. Optional C pointers introduce another bit to keep track of
2019-02-14 23:59:20 +00:00
null, just like {#syntax#}?usize{#endsyntax#}. Note that creating an optional C pointer
is unnecessary as one can use normal {#link|Optional Pointers#}.
< / li >
2019-11-08 20:56:21 +00:00
< li > Supports {#link|Type Coercion#} to and from integers.< / li >
2019-02-14 23:59:20 +00:00
< li > Supports comparison with integers.< / li >
< li > Does not support Zig-only pointer attributes such as alignment. Use normal {#link|Pointers#}
please!< / li >
< / ul >
2020-09-16 03:47:27 +01:00
< p > When a C pointer is pointing to a single struct (not an array), dereference the C pointer to
2019-09-19 16:14:42 +01:00
access to the struct's fields or member data. That syntax looks like
2019-08-19 21:47:16 +01:00
this: < / p >
< p > {#syntax#}ptr_to_struct.*.struct_member{#endsyntax#}< / p >
< p > This is comparable to doing {#syntax#}->{#endsyntax#} in C.< / p >
< p > When a C pointer is pointing to an array of structs, the syntax reverts to this:< / p >
< p > {#syntax#}ptr_to_struct_array[index].struct_member{#endsyntax#}< / p >
2019-02-14 23:59:20 +00:00
{#header_close#}
2018-08-27 22:44:58 +01:00
{#header_open|Exporting a C Library#}
< p >
One of the primary use cases for Zig is exporting a library with the C ABI for other programming languages
2018-09-14 15:35:03 +01:00
to call into. The {#syntax#}export{#endsyntax#} keyword in front of functions, variables, and types causes them to
2018-08-27 22:44:58 +01:00
be part of the library API:
< / p >
< p class = "file" > mathtest.zig< / p >
{#code_begin|syntax#}
export fn add(a: i32, b: i32) i32 {
return a + b;
}
{#code_end#}
2019-05-02 16:59:49 +01:00
< p > To make a static library:< / p >
2018-08-27 22:44:58 +01:00
< pre > < code class = "shell" > $ zig build-lib mathtest.zig
< / code > < / pre >
2019-05-02 16:59:49 +01:00
< p > To make a shared library:< / p >
< pre > < code class = "shell" > $ zig build-lib mathtest.zig -dynamic
2018-08-27 22:44:58 +01:00
< / code > < / pre >
< p > Here is an example with the {#link|Zig Build System#}:< / p >
< p class = "file" > test.c< / p >
< pre > < code class = "cpp" > // This header is generated by zig from mathtest.zig
#include "mathtest.h"
2019-05-02 16:59:49 +01:00
#include < stdio.h>
2018-08-27 22:44:58 +01:00
int main(int argc, char **argv) {
2019-05-02 16:59:49 +01:00
int32_t result = add(42, 1337);
printf("%d\n", result);
2018-08-27 22:44:58 +01:00
return 0;
}< / code > < / pre >
< p class = "file" > build.zig< / p >
{#code_begin|syntax#}
const Builder = @import("std").build.Builder;
pub fn build(b: *Builder) void {
const lib = b.addSharedLibrary("mathtest", "mathtest.zig", b.version(1, 0, 0));
2019-05-02 16:59:49 +01:00
const exe = b.addExecutable("test", null);
2019-12-02 02:27:55 +00:00
exe.addCSourceFile("test.c", & [_][]const u8{"-std=c99"});
2018-08-27 22:44:58 +01:00
exe.linkLibrary(lib);
2019-05-02 16:59:49 +01:00
exe.linkSystemLibrary("c");
2018-08-27 22:44:58 +01:00
b.default_step.dependOn(&exe.step);
breaking changes to zig build API and improved caching
* in Zig build scripts, getOutputPath() is no longer a valid function
to call, unless setOutputDir() was used, or within a custom make()
function. Instead there is more convenient API to use which takes
advantage of the caching system. Search this commit diff for
`exe.run()` for an example.
* Zig build by default enables caching. All build artifacts will go
into zig-cache. If you want to access build artifacts in a convenient
location, it is recommended to add an `install` step. Otherwise
you can use the `run()` API mentioned above to execute programs
directly from their location in the cache. Closes #330.
`addSystemCommand` is available for programs not built with Zig
build.
* Please note that Zig does no cache evicting yet. You may have to
manually delete zig-cache directories periodically to keep disk
usage down. It's planned for this to be a simple Least Recently
Used eviction system eventually.
* `--output`, `--output-lib`, and `--output-h` are removed. Instead,
use `--output-dir` which defaults to the current working directory.
Or take advantage of `--cache on`, which will print the main output
path to stdout, and the other artifacts will be in the same directory
with predictable file names. `--disable-gen-h` is available when
one wants to prevent .h file generation.
* `@cImport` is always independently cached now. Closes #2015.
It always writes the generated Zig code to disk which makes debug
info and compile errors better. No more "TODO: remember C source
location to display here"
* Fix .d file parsing. (Fixes the MacOS CI failure)
* Zig no longer creates "temporary files" other than inside a
zig-cache directory.
This breaks the CLI API that Godbolt uses. The suggested new invocation
can be found in this commit diff, in the changes to `test/cli.zig`.
2019-03-09 03:53:35 +00:00
const run_cmd = exe.run();
2018-08-27 22:44:58 +01:00
const test_step = b.step("test", "Test the program");
test_step.dependOn(&run_cmd.step);
}
{#code_end#}
< p class = "file" > terminal< / p >
2019-05-02 16:59:49 +01:00
< pre > < code class = "shell" > $ zig build test
1379
< / code > < / pre >
2019-03-13 15:54:56 +00:00
{#see_also|export#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Mixing Object Files#}
2017-11-07 08:22:27 +00:00
< p >
You can mix Zig object files with any other object files that respect the C ABI. Example:
< / p >
2018-01-19 08:36:54 +00:00
< p class = "file" > base64.zig< / p >
{#code_begin|syntax#}
2018-01-19 08:03:20 +00:00
const base64 = @import("std").base64;
2017-11-07 08:22:27 +00:00
2018-06-05 03:11:14 +01:00
export fn decode_base_64(
dest_ptr: [*]u8,
dest_len: usize,
source_ptr: [*]const u8,
source_len: usize,
) usize {
2017-11-18 06:42:21 +00:00
const src = source_ptr[0..source_len];
const dest = dest_ptr[0..dest_len];
2017-11-21 04:36:18 +00:00
const base64_decoder = base64.standard_decoder_unsafe;
const decoded_size = base64_decoder.calcSize(src);
base64_decoder.decode(dest[0..decoded_size], src);
2017-11-18 06:42:21 +00:00
return decoded_size;
}
2018-01-19 08:03:20 +00:00
{#code_end#}
2018-01-19 08:36:54 +00:00
< p class = "file" > test.c< / p >
2018-01-19 08:03:20 +00:00
< pre > < code class = "cpp" > // This header is generated by zig from base64.zig
2017-11-07 08:22:27 +00:00
#include "base64.h"
#include < string.h>
#include < stdio.h>
int main(int argc, char **argv) {
const char *encoded = "YWxsIHlvdXIgYmFzZSBhcmUgYmVsb25nIHRvIHVz";
char buf[200];
size_t len = decode_base_64(buf, 200, encoded, strlen(encoded));
buf[len] = 0;
puts(buf);
return 0;
}< / code > < / pre >
2018-01-19 08:36:54 +00:00
< p class = "file" > build.zig< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
const Builder = @import("std").build.Builder;
2017-11-07 08:22:27 +00:00
2018-05-31 15:56:59 +01:00
pub fn build(b: *Builder) void {
2017-11-07 08:22:27 +00:00
const obj = b.addObject("base64", "base64.zig");
2019-07-16 16:50:34 +01:00
const exe = b.addExecutable("test", null);
2019-12-02 02:27:55 +00:00
exe.addCSourceFile("test.c", & [_][]const u8{"-std=c99"});
2017-11-07 08:22:27 +00:00
exe.addObject(obj);
2019-07-16 16:50:34 +01:00
exe.linkSystemLibrary("c");
exe.install();
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-06-08 00:10:45 +01:00
< p class = "file" > terminal< / p >
2018-01-19 08:03:20 +00:00
< pre > < code class = "shell" > $ zig build
2019-07-16 16:50:34 +01:00
$ ./zig-cache/bin/test
2017-11-07 08:22:27 +00:00
all your base are belong to us< / code > < / pre >
2018-01-17 05:22:33 +00:00
{#see_also|Targets|Zig Build System#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_close#}
2019-05-01 23:48:26 +01:00
{#header_open|WebAssembly#}
2019-11-26 00:30:41 +00:00
< p > Zig supports building for WebAssembly out of the box.< / p >
2019-05-01 23:48:26 +01:00
{#header_open|Freestanding#}
2019-05-22 16:12:15 +01:00
< p > For host environments like the web browser and nodejs, build as a library using the freestanding OS target.
2019-05-20 03:26:10 +01:00
Here's an example of running Zig code compiled to WebAssembly with nodejs.< / p >
{#code_begin|lib|math#}
2019-05-01 23:48:26 +01:00
{#target_wasm#}
extern fn print(i32) void;
export fn add(a: i32, b: i32) void {
print(a + b);
}
{#code_end#}
{#header_close#}
2019-05-20 03:26:10 +01:00
< p class = "file" > test.js< / p >
< pre > < code > const fs = require('fs');
const source = fs.readFileSync("./math.wasm");
const typedArray = new Uint8Array(source);
WebAssembly.instantiate(typedArray, {
env: {
print: (result) => { console.log(`The result is ${result}`); }
}}).then(result => {
const add = result.instance.exports.add;
add(1, 2);
});< / code > < / pre >
< pre > < code > $ node test.js
The result is 3< / code > < / pre >
2019-05-01 23:48:26 +01:00
{#header_open|WASI#}
2020-02-27 19:41:44 +00:00
< p > Zig's support for WebAssembly System Interface (WASI) is under active development.
Example of using the standard library and reading command line arguments:< / p >
2020-06-11 21:06:57 +01:00
{#code_begin|exe|args#}
2019-05-01 23:48:26 +01:00
{#target_wasi#}
const std = @import("std");
pub fn main() !void {
2020-09-29 08:24:17 +01:00
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = &general_purpose_allocator.allocator;
const args = try std.process.argsAlloc(gpa);
defer std.process.argsFree(gpa, args);
2019-05-01 23:48:26 +01:00
for (args) |arg, i| {
2020-09-29 08:24:17 +01:00
std.debug.print("{}: {}\n", .{ i, arg });
2019-05-01 23:48:26 +01:00
}
}
{#code_end#}
2020-06-11 21:06:57 +01:00
< pre > < code > $ wasmtime args.wasm 123 hello
0: args.wasm
2019-05-20 03:26:10 +01:00
1: 123
2: hello< / code > < / pre >
2020-06-11 21:06:57 +01:00
< p > A more interesting example would be extracting the list of preopens from the runtime.
This is now supported in the standard library via {#syntax#}std.fs.wasi.PreopenList{#endsyntax#}:< / p >
{#code_begin|exe|preopens#}
{#target_wasi#}
const std = @import("std");
const PreopenList = std.fs.wasi.PreopenList;
pub fn main() !void {
2020-10-10 09:52:36 +01:00
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = &general_purpose_allocator.allocator;
var preopens = PreopenList.init(gpa);
2020-06-11 21:06:57 +01:00
defer preopens.deinit();
try preopens.populate();
for (preopens.asSlice()) |preopen, i| {
2020-06-19 10:38:22 +01:00
std.debug.print("{}: {}\n", .{ i, preopen });
2020-06-11 21:06:57 +01:00
}
}
{#code_end#}
< pre > < code > $ wasmtime --dir=. preopens.wasm
2020-06-23 20:54:36 +01:00
0: Preopen{ .fd = 3, .type = PreopenType{ .Dir = '.' } }
2020-06-11 21:06:57 +01:00
< / code > < / pre >
2019-05-01 23:48:26 +01:00
{#header_close#}
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|Targets#}
2017-11-07 08:22:27 +00:00
< p >
Zig supports generating code for all targets that LLVM supports. Here is
what it looks like to execute < code > zig targets< / code > on a Linux x86_64
computer:
< / p >
2018-01-19 08:03:20 +00:00
< pre > < code class = "shell" > $ zig targets
2017-11-07 08:22:27 +00:00
Architectures:
2019-03-13 17:04:55 +00:00
arm
v8_4a
v8_3a
v8_2a
v8_1a
v8
v8r
v8m_baseline
v8m_mainline
v7
v7em
v7m
v7s
v7k
v7ve
v6
v6m
v6k
v6t2
v5
v5te
v4t
2017-11-07 08:22:27 +00:00
armeb
2019-03-13 17:04:55 +00:00
v8_4a
v8_3a
v8_2a
v8_1a
v8
v8r
v8m_baseline
v8m_mainline
v7
v7em
v7m
v7s
v7k
v7ve
v6
v6m
v6k
v6t2
v5
v5te
v4t
2017-11-07 08:22:27 +00:00
aarch64
2019-03-13 17:04:55 +00:00
v8_4a
v8_3a
v8_2a
v8_1a
v8
v8r
v8m_baseline
v8m_mainline
2017-11-07 08:22:27 +00:00
aarch64_be
2019-03-13 17:04:55 +00:00
v8_4a
v8_3a
v8_2a
v8_1a
v8
v8r
v8m_baseline
v8m_mainline
2017-11-07 08:22:27 +00:00
avr
bpfel
bpfeb
hexagon
mips
mipsel
mips64
mips64el
msp430
powerpc
powerpc64
powerpc64le
r600
amdgcn
2018-01-19 08:03:20 +00:00
riscv32
riscv64
2017-11-07 08:22:27 +00:00
sparc
sparcv9
sparcel
s390x
thumb
2019-03-13 17:04:55 +00:00
v8_4a
v8_3a
v8_2a
v8_1a
v8
v8r
v8m_baseline
v8m_mainline
v7
v7em
v7m
v7s
v7k
v7ve
v6
v6m
v6k
v6t2
v5
v5te
v4t
2017-11-07 08:22:27 +00:00
thumbeb
2019-03-13 17:04:55 +00:00
v8_4a
v8_3a
v8_2a
v8_1a
v8
v8r
v8m_baseline
v8m_mainline
v7
v7em
v7m
v7s
v7k
v7ve
v6
v6m
v6k
v6t2
v5
v5te
v4t
2017-11-07 08:22:27 +00:00
i386
x86_64 (native)
xcore
nvptx
nvptx64
lanai
wasm32
wasm64
Operating Systems:
freestanding
2018-01-19 08:03:20 +00:00
ananas
2017-11-07 08:22:27 +00:00
cloudabi
dragonfly
freebsd
2018-01-19 08:03:20 +00:00
fuchsia
2017-11-07 08:22:27 +00:00
ios
kfreebsd
linux (native)
lv2
macosx
netbsd
openbsd
solaris
windows
haiku
minix
rtems
nacl
cnk
aix
cuda
nvcl
amdhsa
ps4
elfiamcu
tvos
watchos
mesa3d
2018-01-19 08:03:20 +00:00
contiki
2019-03-13 17:04:55 +00:00
amdpal
2018-01-19 08:03:20 +00:00
zen
2019-03-13 17:04:55 +00:00
uefi
2017-11-07 08:22:27 +00:00
2019-03-13 17:04:55 +00:00
C ABIs:
none
2017-11-07 08:22:27 +00:00
gnu (native)
2019-03-13 17:04:55 +00:00
gnuabin32
2017-11-07 08:22:27 +00:00
gnuabi64
gnueabi
gnueabihf
gnux32
code16
eabi
eabihf
android
musl
musleabi
musleabihf
msvc
itanium
cygnus
2018-01-19 08:03:20 +00:00
coreclr
2019-03-19 19:04:29 +00:00
simulator
Available libcs:
aarch64_be-linux-gnu
aarch64_be-linux-musl
aarch64-linux-gnu
aarch64-linux-musleabi
armeb-linux-gnueabi
armeb-linux-gnueabihf
armeb-linux-musleabi
armeb-linux-musleabihf
arm-linux-gnueabi
arm-linux-gnueabihf
arm-linux-musleabi
arm-linux-musleabihf
i386-linux-gnu
i386-linux-musl
mips64el-linux-gnuabi64
mips64el-linux-gnuabin32
mips64el-linux-musl
mips64-linux-gnuabi64
mips64-linux-gnuabin32
mips64-linux-musl
mipsel-linux-gnu
mipsel-linux-musl
mips-linux-gnu
mips-linux-musl
nios2-linux-gnu
powerpc64le-linux-gnu
powerpc64le-linux-musl
powerpc64-linux-gnu
powerpc64-linux-musl
powerpc-linux-gnu
powerpc-linux-musl
riscv32-linux-musl
riscv64-linux-gnu
riscv64-linux-musl
s390x-linux-gnu
s390x-linux-musl
sparc-linux-gnu
sparcv9-linux-gnu
2019-05-20 03:26:10 +01:00
wasm32-freestanding-musl
2019-03-19 19:04:29 +00:00
x86_64-linux-gnu
x86_64-linux-gnux32
x86_64-linux-musl< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
2019-02-22 13:49:27 +00:00
The Zig Standard Library ({#syntax#}@import("std"){#endsyntax#}) has architecture, environment, and operating system
2018-07-14 16:52:48 +01:00
abstractions, and thus takes additional work to support more platforms.
Not all standard library code requires operating system abstractions, however,
2020-01-28 02:38:43 +00:00
so things such as generic data structures work on all above platforms.
2017-11-07 08:22:27 +00:00
< / p >
2018-07-14 16:52:48 +01:00
< p > The current list of targets supported by the Zig Standard Library is:< / p >
< ul >
< li > Linux x86_64< / li >
< li > Windows x86_64< / li >
2019-03-25 16:55:45 +00:00
< li > macOS x86_64< / li >
2018-07-14 16:52:48 +01:00
< / ul >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Style Guide#}
2017-11-07 08:22:27 +00:00
< p >
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.
< / p >
2018-01-17 04:19:05 +00:00
{#header_open|Whitespace#}
2017-11-07 08:22:27 +00:00
< ul >
< li >
4 space indentation
< / li >
< li >
Open braces on same line, unless you need to wrap.
< / li >
< li > If a list of things is longer than 2, put each item on its own line and
2018-11-16 18:33:58 +00:00
exercise the ability to put an extra comma at the end.
2017-11-07 08:22:27 +00:00
< / li >
< li >
Line length: aim for 100; use common sense.
< / li >
< / ul >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Names#}
2017-11-07 08:22:27 +00:00
< p >
2018-09-14 15:35:03 +01:00
Roughly speaking: {#syntax#}camelCaseFunctionName{#endsyntax#}, {#syntax#}TitleCaseTypeName{#endsyntax#},
{#syntax#}snake_case_variable_name{#endsyntax#}. More precisely:
2017-11-07 08:22:27 +00:00
< / p >
< ul >
< li >
2019-02-28 15:11:32 +00:00
If {#syntax#}x{#endsyntax#} is a {#syntax#}type{#endsyntax#}
then {#syntax#}x{#endsyntax#} should be {#syntax#}TitleCase{#endsyntax#}, unless it
is a {#syntax#}struct{#endsyntax#} with 0 fields and is never meant to be instantiated,
2019-03-01 22:23:27 +00:00
in which case it is considered to be a "namespace" and uses {#syntax#}snake_case{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / li >
< li >
2019-02-28 15:11:32 +00:00
If {#syntax#}x{#endsyntax#} is callable, and {#syntax#}x{#endsyntax#}'s return type is
{#syntax#}type{#endsyntax#}, then {#syntax#}x{#endsyntax#} should be {#syntax#}TitleCase{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / li >
< li >
2019-02-28 15:11:32 +00:00
If {#syntax#}x{#endsyntax#} is otherwise callable, then {#syntax#}x{#endsyntax#} should
be {#syntax#}camelCase{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / li >
< li >
2018-09-14 15:35:03 +01:00
Otherwise, {#syntax#}x{#endsyntax#} should be {#syntax#}snake_case{#endsyntax#}.
2017-11-07 08:22:27 +00:00
< / li >
< / ul >
< p >
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.
< / p >
< p >
2020-05-02 22:28:44 +01:00
File names fall into two categories: types and namespaces. If the file
(implicity a struct) has top level fields, it should be named like any
other struct with fields using {#syntax#}TitleCase{#endsyntax#}. Otherwise,
it should use {#syntax#}snake_case{#endsyntax#}. Directory names should be
{#syntax#}snake_case{#endsyntax#}.
< / p >
< p >
2017-11-07 08:22:27 +00:00
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
2018-09-14 15:35:03 +01:00
{#syntax#}ENOENT{#endsyntax#}, follow the established convention.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Examples#}
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
const namespace_name = @import("dir_name/file_name.zig");
2020-05-02 22:28:44 +01:00
const TypeName = @import("dir_name/TypeName.zig");
2017-11-07 08:22:27 +00:00
var global_var: i32 = undefined;
const const_name = 42;
const primitive_type_alias = f32;
const string_alias = []u8;
2019-02-28 15:11:32 +00:00
const StructName = struct {
field: i32,
};
2017-11-07 08:22:27 +00:00
const StructAlias = StructName;
2018-01-25 09:10:11 +00:00
fn functionName(param_name: TypeName) void {
2017-11-07 08:22:27 +00:00
var functionPointer = functionName;
functionPointer();
functionPointer = otherFunction;
functionPointer();
}
const functionAlias = functionName;
2018-01-25 09:10:11 +00:00
fn ListTemplateFunction(comptime ChildType: type, comptime fixed_size: usize) type {
2017-11-07 08:22:27 +00:00
return List(ChildType, fixed_size);
}
2018-01-25 09:10:11 +00:00
fn ShortList(comptime T: type, comptime n: usize) type {
2018-11-13 13:08:37 +00:00
return struct {
2017-11-07 08:22:27 +00:00
field_name: [n]T,
2018-01-25 09:10:11 +00:00
fn methodName() void {}
2018-01-19 08:03:20 +00:00
};
2017-11-07 08:22:27 +00:00
}
// The word XML loses its casing when used in Zig identifiers.
const xml_document =
2018-01-19 08:03:20 +00:00
\\<?xml version="1.0" encoding="UTF-8"?>
\\< document >
\\< / document >
2017-11-07 08:22:27 +00:00
;
2019-02-28 15:11:32 +00:00
const XmlParser = struct {
field: i32,
};
2017-11-07 08:22:27 +00:00
// The initials BE (Big Endian) are just another word in Zig identifier names.
2018-01-25 09:10:11 +00:00
fn readU32Be() u32 {}
2018-01-19 08:03:20 +00:00
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
See the Zig Standard Library for more examples.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_close#}
2018-02-01 01:42:27 +00:00
{#header_open|Source Encoding#}
< p > Zig source code is encoded in UTF-8. An invalid UTF-8 byte sequence results in a compile error.< / p >
< p > Throughout all zig source code (including in comments), some codepoints are never allowed:< / p >
< ul >
< li > Ascii control characters, except for U+000a (LF): U+0000 - U+0009, U+000b - U+0001f, U+007f. (Note that Windows line endings (CRLF) are not allowed, and hard tabs are not allowed.)< / li >
< li > Non-Ascii Unicode line endings: U+0085 (NEL), U+2028 (LS), U+2029 (PS).< / li >
< / ul >
2019-10-06 22:00:53 +01:00
< p > The codepoint U+000a (LF) (which is encoded as the single-byte value 0x0a) is the line terminator character. This character always terminates a line of zig source code (except possibly the last line of the file).< / p >
2018-05-25 02:27:44 +01:00
< p > For some discussion on the rationale behind these design decisions, see < a href = "https://github.com/ziglang/zig/issues/663" > issue #663< / a > < / p >
2018-02-01 01:42:27 +00:00
{#header_close#}
2019-03-13 17:04:55 +00:00
{#header_open|Keyword Reference#}
2020-08-24 23:29:53 +01:00
< div class = "table-wrapper" >
2020-08-24 16:59:55 +01:00
< table >
< tr >
< th >
Keyword
< / th >
< th >
Description
< / th >
< / tr >
< tr >
< td >
< pre > {#syntax#}align{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
{#syntax#}align{#endsyntax#} can be used to specify the alignment of a pointer.
It can also be used after a variable or function declaration to specify the alignment of pointers to that variable or function.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|Alignment#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}allowzero{#endsyntax#}< / pre >
< / td >
< td >
The pointer attribute {#syntax#}allowzero{#endsyntax#} allows a pointer to have address zero.
< ul >
< li > See also {#link|allowzero#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}and{#endsyntax#}< / pre >
< / td >
< td >
The boolean operator {#syntax#}and{#endsyntax#}.
< ul >
< li > See also {#link|Operators#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}anyframe{#endsyntax#}< / pre >
< / td >
< td >
{#syntax#}anyframe{#endsyntax#} can be used as a type for variables which hold pointers to function frames.
< ul >
< li > See also {#link|Async Functions#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}anytype{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
Function parameters and struct fields can be declared with {#syntax#}anytype{#endsyntax#} in place of the type.
The type will be inferred where the function is called or the struct is instantiated.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|Function Parameter Type Inference#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}asm{#endsyntax#}< / pre >
< / td >
< td >
{#syntax#}asm{#endsyntax#} begins an inline assembly expression. This allows for directly controlling the machine code generated on compilation.
< ul >
< li > See also {#link|Assembly#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}async{#endsyntax#}< / pre >
< / td >
< td >
{#syntax#}async{#endsyntax#} can be used before a function call to get a pointer to the function's frame when it suspends.
< ul >
< li > See also {#link|Async Functions#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}await{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
{#syntax#}await{#endsyntax#} can be used to suspend the current function until the frame provided after the {#syntax#}await{#endsyntax#} completes.
{#syntax#}await{#endsyntax#} copies the value returned from the target function's frame to the caller.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|Async Functions#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}break{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
{#syntax#}break{#endsyntax#} can be used with a block label to return a value from the block.
It can also be used to exit a loop before iteration completes naturally.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|blocks#}, {#link|while#}, {#link|for#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}catch{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
{#syntax#}catch{#endsyntax#} can be used to evaluate an expression if the expression before it evaluates to an error.
The expression after the {#syntax#}catch{#endsyntax#} can optionally capture the error value.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|catch#}, {#link|Operators#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}comptime{#endsyntax#}< / pre >
< / td >
< td >
{#syntax#}comptime{#endsyntax#} before a declaration can be used to label variables or function parameters as known at compile time.
It can also be used to guarantee an expression is run at compile time.
< ul >
< li > See also {#link|comptime#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}const{#endsyntax#}< / pre >
< / td >
< td >
{#syntax#}const{#endsyntax#} declares a variable that can not be modified.
2020-08-24 19:12:23 +01:00
Used as a pointer attribute, it denotes the value referenced by the pointer cannot be modified.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|Variables#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}continue{#endsyntax#}< / pre >
< / td >
< td >
{#syntax#}continue{#endsyntax#} can be used in a loop to jump back to the beginning of the loop.
< ul >
< li > See also {#link|while#}, {#link|for#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}defer{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
{#syntax#}defer{#endsyntax#} will execute an expression when control flow leaves the current block.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|defer#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}else{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
{#syntax#}else{#endsyntax#} can be used to provide an alternate branch for {#syntax#}if{#endsyntax#}, {#syntax#}switch{#endsyntax#},
{#syntax#}while{#endsyntax#}, and {#syntax#}for{#endsyntax#} expressions.
2020-08-24 16:59:55 +01:00
< ul >
< li > If used after an if expression, the else branch will be executed if the test value returns false, null, or an error.< / li >
< li > If used within a switch expression, the else branch will be executed if the test value matches no other cases.< / li >
< li > If used after a loop expression, the else branch will be executed if the loop finishes without breaking.< / li >
< li > See also {#link|if#}, {#link|switch#}, {#link|while#}, {#link|for#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}enum{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
{#syntax#}enum{#endsyntax#} defines an enum type.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|enum#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}errdefer{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
{#syntax#}errdefer{#endsyntax#} will execute an expression when control flow leaves the current block if the function returns an error.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|errdefer#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}error{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
{#syntax#}error{#endsyntax#} defines an error type.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|Errors#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}export{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
{#syntax#}export{#endsyntax#} makes a function or variable externally visible in the generated object file.
Exported functions default to the C calling convention.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|Functions#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}extern{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
{#syntax#}extern{#endsyntax#} can be used to declare a function or variable that will be resolved at link time, when linking statically
or at runtime, when linking dynamically.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|Functions#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}false{#endsyntax#}< / pre >
< / td >
< td >
The boolean value {#syntax#}false{#endsyntax#}.
< ul >
< li > See also {#link|Primitive Values#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}fn{#endsyntax#}< / pre >
< / td >
< td >
{#syntax#}fn{#endsyntax#} declares a function.
< ul >
< li > See also {#link|Functions#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}for{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
A {#syntax#}for{#endsyntax#} expression can be used to iterate over the elements of a slice, array, or tuple.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|for#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}if{#endsyntax#}< / pre >
< / td >
< td >
An {#syntax#}if{#endsyntax#} expression can test boolean expressions, optional values, or error unions.
For optional values or error unions, the if expression can capture the unwrapped value.
< ul >
< li > See also {#link|if#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}inline{#endsyntax#}< / pre >
< / td >
< td >
{#syntax#}inline{#endsyntax#} can be used to label a loop expression such that it will be unrolled at compile time.
It can also be used to force a function to be inlined at all call sites.
< ul >
< li > See also {#link|inline while#}, {#link|inline for#}, {#link|Functions#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}noalias{#endsyntax#}< / pre >
< / td >
< td >
The {#syntax#}noalias{#endsyntax#} keyword.
< ul >
< li > TODO add documentation for noalias< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}nosuspend{#endsyntax#}< / pre >
< / td >
< td >
The {#syntax#}nosuspend{#endsyntax#} keyword.
< ul >
< li > TODO add documentation for nosuspend< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}null{#endsyntax#}< / pre >
< / td >
< td >
The optional value {#syntax#}null{#endsyntax#}.
< ul >
< li > See also {#link|null#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}or{#endsyntax#}< / pre >
< / td >
< td >
The boolean operator {#syntax#}or{#endsyntax#}.
< ul >
< li > See also {#link|Operators#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}orelse{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
{#syntax#}orelse{#endsyntax#} can be used to evaluate an expression if the expression before it evaluates to null.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|Optionals#}, {#link|Operators#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}packed{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
The {#syntax#}packed{#endsyntax#} keyword before a struct definition changes the struct's in-memory layout
to the guaranteed {#syntax#}packed{#endsyntax#} layout.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|packed struct#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}pub{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
The {#syntax#}pub{#endsyntax#} in front of a top level declaration makes the declaration available
to reference from a different file than the one it is declared in.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|import#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}resume{#endsyntax#}< / pre >
< / td >
< td >
{#syntax#}resume{#endsyntax#} will continue execution of a function frame after the point the function was suspended.
< ul >
< li > See also {#link|Suspend and Resume#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}return{#endsyntax#}< / pre >
< / td >
< td >
{#syntax#}return{#endsyntax#} exits a function with a value.
< ul >
< li > See also {#link|Functions#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}linksection{#endsyntax#}< / pre >
< / td >
< td >
The {#syntax#}linksection{#endsyntax#} keyword.
< ul >
< li > TODO add documentation for linksection< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}struct{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
{#syntax#}struct{#endsyntax#} defines a struct.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|struct#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}suspend{#endsyntax#}< / pre >
< / td >
< td >
{#syntax#}suspend{#endsyntax#} will cause control flow to return to the call site or resumer of the function.
2020-08-24 19:12:23 +01:00
{#syntax#}suspend{#endsyntax#} can also be used before a block within a function,
to allow the function access to its frame before control flow returns to the call site.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|Suspend and Resume#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}switch{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
A {#syntax#}switch{#endsyntax#} expression can be used to test values of a common type.
{#syntax#}switch{#endsyntax#} cases can capture field values of a {#link|Tagged union#}.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|switch#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}test{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
The {#syntax#}test{#endsyntax#} keyword can be used to denote a top-level block of code
used to make sure behavior meets expectations.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|Zig Test#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}threadlocal{#endsyntax#}< / pre >
< / td >
< td >
{#syntax#}threadlocal{#endsyntax#} can be used to specify a variable as thread-local.
< ul >
< li > See also {#link|Thread Local Variables#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}true{#endsyntax#}< / pre >
< / td >
< td >
The boolean value {#syntax#}true{#endsyntax#}.
< ul >
< li > See also {#link|Primitive Values#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}try{#endsyntax#}< / pre >
< / td >
< td >
{#syntax#}try{#endsyntax#} evaluates an error union expression.
If it is an error, it returns from the current function with the same error.
Otherwise, the expression results in the unwrapped value.
< ul >
< li > See also {#link|try#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}undefined{#endsyntax#}< / pre >
< / td >
< td >
{#syntax#}undefined{#endsyntax#} can be used to leave a value uninitialized.
< ul >
< li > See also {#link|undefined#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}union{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
{#syntax#}union{#endsyntax#} defines a union.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|union#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}unreachable{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
{#syntax#}unreachable{#endsyntax#} can be used to assert that control flow will never happen upon a particular location.
2020-08-24 16:59:55 +01:00
Depending on the build mode, {#syntax#}unreachable{#endsyntax#} may emit a panic.
< ul >
< li > Emits a panic in {#syntax#}Debug{#endsyntax#} and {#syntax#}ReleaseSafe{#endsyntax#} mode, or when using < code > zig test< / code > .< / li >
< li > Does not emit a panic in {#syntax#}ReleaseFast{#endsyntax#} mode, unless < code > zig test< / code > is being used.< / li >
< li > See also {#link|unreachable#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}usingnamespace{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
{#syntax#}usingnamespace{#endsyntax#} is a top-level declaration that imports all the public declarations of the operand,
which must be a struct, union, or enum, into the current scope.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|usingnamespace#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}var{#endsyntax#}< / pre >
< / td >
< td >
{#syntax#}var{#endsyntax#} declares a variable that may be modified.
< ul >
< li > See also {#link|Variables#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}volatile{#endsyntax#}< / pre >
< / td >
< td >
{#syntax#}volatile{#endsyntax#} can be used to denote loads or stores of a pointer have side effects.
It can also modify an inline assembly expression to denote it has side effects.
< ul >
< li > See also {#link|volatile#}, {#link|Assembly#}< / li >
< / ul >
< / td >
< / tr >
< tr >
< td >
< pre > {#syntax#}while{#endsyntax#}< / pre >
< / td >
< td >
2020-08-24 19:12:23 +01:00
A {#syntax#}while{#endsyntax#} expression can be used to repeatedly test a boolean, optional, or error union expression,
and cease looping when that expression evaluates to false, null, or an error, respectively.
2020-08-24 16:59:55 +01:00
< ul >
< li > See also {#link|while#}< / li >
< / ul >
< / td >
< / tr >
< / table >
2020-08-24 23:29:53 +01:00
< / div >
2019-03-13 17:04:55 +00:00
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|Grammar#}
2018-11-17 06:38:35 +00:00
< pre > < code > Root < - skip ContainerMembers eof
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
# *** Top level ***
ContainerMembers
2018-11-17 06:38:35 +00:00
< - TestDecl ContainerMembers
2018-11-14 07:56:26 +00:00
/ TopLevelComptime ContainerMembers
/ KEYWORD_pub? TopLevelDecl ContainerMembers
2019-10-21 20:22:08 +01:00
/ ContainerField COMMA ContainerMembers
/ ContainerField
2018-11-14 07:56:26 +00:00
/
2017-11-07 08:22:27 +00:00
2020-01-14 19:24:39 +00:00
TestDecl < - KEYWORD_test STRINGLITERALSINGLE Block
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
TopLevelComptime < - KEYWORD_comptime BlockExpr
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
TopLevelDecl
2020-01-14 19:24:39 +00:00
< - (KEYWORD_export / KEYWORD_extern STRINGLITERALSINGLE? / KEYWORD_inline)? FnProto (SEMICOLON / Block)
/ (KEYWORD_export / KEYWORD_extern STRINGLITERALSINGLE?)? KEYWORD_threadlocal? VarDecl
2019-10-06 21:39:27 +01:00
/ KEYWORD_usingnamespace Expr SEMICOLON
2017-11-07 08:22:27 +00:00
2020-07-11 12:08:20 +01:00
FnProto < - KEYWORD_fn IDENTIFIER? LPAREN ParamDeclList RPAREN ByteAlign? LinkSection? EXCLAMATIONMARK? (KEYWORD_anytype / TypeExpr)
2017-12-19 06:19:49 +00:00
2018-11-17 06:38:35 +00:00
VarDecl < - (KEYWORD_const / KEYWORD_var) IDENTIFIER (COLON TypeExpr)? ByteAlign? LinkSection? (EQUAL Expr)? SEMICOLON
2017-11-07 08:22:27 +00:00
2020-05-15 21:38:40 +01:00
ContainerField < - KEYWORD_comptime? IDENTIFIER (COLON TypeExpr)? (EQUAL Expr)?
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
# *** Block Level ***
Statement
2018-11-17 06:38:35 +00:00
< - KEYWORD_comptime? VarDecl
2018-11-14 07:56:26 +00:00
/ KEYWORD_comptime BlockExprStatement
2020-05-14 09:19:14 +01:00
/ KEYWORD_nosuspend BlockExprStatement
2018-11-14 07:56:26 +00:00
/ KEYWORD_suspend (SEMICOLON / BlockExprStatement)
/ KEYWORD_defer BlockExprStatement
/ KEYWORD_errdefer BlockExprStatement
/ IfStatement
/ LabeledStatement
/ SwitchExpr
/ AssignExpr SEMICOLON
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
IfStatement
2018-11-17 06:38:35 +00:00
< - IfPrefix BlockExpr ( KEYWORD_else Payload? Statement )?
2018-11-14 07:56:26 +00:00
/ IfPrefix AssignExpr ( SEMICOLON / KEYWORD_else Payload? Statement )
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
LabeledStatement < - BlockLabel? (Block / LoopStatement)
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
LoopStatement < - KEYWORD_inline? (ForStatement / WhileStatement)
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
ForStatement
2018-11-17 06:38:35 +00:00
< - ForPrefix BlockExpr ( KEYWORD_else Statement )?
2018-11-14 07:56:26 +00:00
/ ForPrefix AssignExpr ( SEMICOLON / KEYWORD_else Statement )
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
WhileStatement
2018-11-17 06:38:35 +00:00
< - WhilePrefix BlockExpr ( KEYWORD_else Payload? Statement )?
2018-11-14 07:56:26 +00:00
/ WhilePrefix AssignExpr ( SEMICOLON / KEYWORD_else Payload? Statement )
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
BlockExprStatement
2018-11-17 06:38:35 +00:00
< - BlockExpr
2018-11-14 07:56:26 +00:00
/ AssignExpr SEMICOLON
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
BlockExpr < - BlockLabel? Block
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
# *** Expression Level ***
2018-11-17 06:38:35 +00:00
AssignExpr < - Expr (AssignOp Expr)?
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
Expr < - KEYWORD_try* BoolOrExpr
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
BoolOrExpr < - BoolAndExpr (KEYWORD_or BoolAndExpr)*
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
BoolAndExpr < - CompareExpr (KEYWORD_and CompareExpr)*
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
CompareExpr < - BitwiseExpr (CompareOp BitwiseExpr)?
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
BitwiseExpr < - BitShiftExpr (BitwiseOp BitShiftExpr)*
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
BitShiftExpr < - AdditionExpr (BitShiftOp AdditionExpr)*
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
AdditionExpr < - MultiplyExpr (AdditionOp MultiplyExpr)*
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
MultiplyExpr < - PrefixExpr (MultiplyOp PrefixExpr)*
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
PrefixExpr < - PrefixOp* PrimaryExpr
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
PrimaryExpr
2018-11-17 06:38:35 +00:00
< - AsmExpr
2018-11-14 07:56:26 +00:00
/ IfExpr
/ KEYWORD_break BreakLabel? Expr?
/ KEYWORD_comptime Expr
2020-05-14 09:19:14 +01:00
/ KEYWORD_nosuspend Expr
2018-11-14 07:56:26 +00:00
/ KEYWORD_continue BreakLabel?
/ KEYWORD_resume Expr
/ KEYWORD_return Expr?
2019-03-22 08:01:30 +00:00
/ BlockLabel? LoopExpr
/ Block
2018-11-14 07:56:26 +00:00
/ CurlySuffixExpr
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
IfExpr < - IfPrefix Expr (KEYWORD_else Payload? Expr)?
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
Block < - LBRACE Statement* RBRACE
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
LoopExpr < - KEYWORD_inline? (ForExpr / WhileExpr)
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
ForExpr < - ForPrefix Expr (KEYWORD_else Expr)?
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
WhileExpr < - WhilePrefix Expr (KEYWORD_else Payload? Expr)?
2017-11-07 08:22:27 +00:00
2019-04-24 05:02:10 +01:00
CurlySuffixExpr < - TypeExpr InitList?
2018-11-14 07:56:26 +00:00
InitList
2018-11-17 06:38:35 +00:00
< - LBRACE FieldInit (COMMA FieldInit)* COMMA? RBRACE
2018-11-14 07:56:26 +00:00
/ LBRACE Expr (COMMA Expr)* COMMA? RBRACE
/ LBRACE RBRACE
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
TypeExpr < - PrefixTypeOp* ErrorUnionExpr
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
ErrorUnionExpr < - SuffixExpr (EXCLAMATIONMARK TypeExpr)?
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
SuffixExpr
2019-08-16 10:24:06 +01:00
< - KEYWORD_async PrimaryTypeExpr SuffixOp* FnCallArguments
2018-11-17 13:36:36 +00:00
/ PrimaryTypeExpr (SuffixOp / FnCallArguments)*
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
PrimaryTypeExpr
2018-11-17 13:36:36 +00:00
< - BUILTINIDENTIFIER FnCallArguments
2018-11-14 07:56:26 +00:00
/ CHAR_LITERAL
/ ContainerDecl
2019-05-11 19:26:41 +01:00
/ DOT IDENTIFIER
2020-01-12 08:35:30 +00:00
/ DOT InitList
2018-11-14 07:56:26 +00:00
/ ErrorSetDecl
/ FLOAT
/ FnProto
/ GroupedExpr
/ LabeledTypeExpr
/ IDENTIFIER
/ IfTypeExpr
/ INTEGER
/ KEYWORD_comptime TypeExpr
/ KEYWORD_error DOT IDENTIFIER
/ KEYWORD_false
/ KEYWORD_null
2020-05-15 21:38:40 +01:00
/ KEYWORD_anyframe
2018-11-14 07:56:26 +00:00
/ KEYWORD_true
/ KEYWORD_undefined
/ KEYWORD_unreachable
/ STRINGLITERAL
/ SwitchExpr
2018-01-07 21:51:46 +00:00
2018-11-17 06:38:35 +00:00
ContainerDecl < - (KEYWORD_extern / KEYWORD_packed)? ContainerDeclAuto
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
ErrorSetDecl < - KEYWORD_error LBRACE IdentifierList RBRACE
2018-02-26 05:04:11 +00:00
2018-11-17 06:38:35 +00:00
GroupedExpr < - LPAREN Expr RPAREN
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
IfTypeExpr < - IfPrefix TypeExpr (KEYWORD_else Payload? TypeExpr)?
2018-02-20 05:05:38 +00:00
2018-11-14 07:56:26 +00:00
LabeledTypeExpr
2018-11-17 06:38:35 +00:00
< - BlockLabel Block
2018-11-14 07:56:26 +00:00
/ BlockLabel? LoopTypeExpr
2018-03-01 03:18:48 +00:00
2018-11-17 06:38:35 +00:00
LoopTypeExpr < - KEYWORD_inline? (ForTypeExpr / WhileTypeExpr)
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
ForTypeExpr < - ForPrefix TypeExpr (KEYWORD_else TypeExpr)?
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
WhileTypeExpr < - WhilePrefix TypeExpr (KEYWORD_else Payload? TypeExpr)?
2018-02-26 05:04:11 +00:00
2018-11-17 06:38:35 +00:00
SwitchExpr < - KEYWORD_switch LPAREN Expr RPAREN LBRACE SwitchProngList RBRACE
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
# *** Assembly ***
2018-11-17 06:38:35 +00:00
AsmExpr < - KEYWORD_asm KEYWORD_volatile? LPAREN STRINGLITERAL AsmOutput? RPAREN
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
AsmOutput < - COLON AsmOutputList AsmInput?
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
AsmOutputItem < - LBRACKET IDENTIFIER RBRACKET STRINGLITERAL LPAREN (MINUSRARROW TypeExpr / IDENTIFIER) RPAREN
2017-11-07 08:22:27 +00:00
2018-11-17 13:36:36 +00:00
AsmInput < - COLON AsmInputList AsmClobbers?
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
AsmInputItem < - LBRACKET IDENTIFIER RBRACKET STRINGLITERAL LPAREN Expr RPAREN
2017-11-07 08:22:27 +00:00
2018-11-17 13:36:36 +00:00
AsmClobbers < - COLON StringList
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
# *** Helper grammar ***
2018-11-17 06:38:35 +00:00
BreakLabel < - COLON IDENTIFIER
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
BlockLabel < - IDENTIFIER COLON
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
FieldInit < - DOT IDENTIFIER EQUAL Expr
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
WhileContinueExpr < - COLON LPAREN AssignExpr RPAREN
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
LinkSection < - KEYWORD_linksection LPAREN Expr RPAREN
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
ParamDecl < - (KEYWORD_noalias / KEYWORD_comptime)? (IDENTIFIER COLON)? ParamType
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
ParamType
2020-07-11 12:08:20 +01:00
< - KEYWORD_anytype
2018-11-14 07:56:26 +00:00
/ DOT3
/ TypeExpr
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
# Control flow prefixes
2018-11-17 06:38:35 +00:00
IfPrefix < - KEYWORD_if LPAREN Expr RPAREN PtrPayload?
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
WhilePrefix < - KEYWORD_while LPAREN Expr RPAREN PtrPayload? WhileContinueExpr?
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
ForPrefix < - KEYWORD_for LPAREN Expr RPAREN PtrIndexPayload
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
# Payloads
2018-11-17 06:38:35 +00:00
Payload < - PIPE IDENTIFIER PIPE
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
PtrPayload < - PIPE ASTERISK? IDENTIFIER PIPE
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
PtrIndexPayload < - PIPE ASTERISK? IDENTIFIER (COMMA IDENTIFIER)? PIPE
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
# Switch specific
2018-11-17 06:38:35 +00:00
SwitchProng < - SwitchCase EQUALRARROW PtrPayload? AssignExpr
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
SwitchCase
2018-11-17 06:38:35 +00:00
< - SwitchItem (COMMA SwitchItem)* COMMA?
2018-11-14 07:56:26 +00:00
/ KEYWORD_else
2017-11-07 08:22:27 +00:00
2018-11-17 06:38:35 +00:00
SwitchItem < - Expr (DOT3 Expr)?
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
# Operators
AssignOp
2018-11-17 06:38:35 +00:00
< - ASTERISKEQUAL
2018-11-14 07:56:26 +00:00
/ SLASHEQUAL
/ PERCENTEQUAL
/ PLUSEQUAL
/ MINUSEQUAL
/ LARROW2EQUAL
/ RARROW2EQUAL
/ AMPERSANDEQUAL
/ CARETEQUAL
/ PIPEEQUAL
/ ASTERISKPERCENTEQUAL
/ PLUSPERCENTEQUAL
/ MINUSPERCENTEQUAL
/ EQUAL
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
CompareOp
2018-11-17 06:38:35 +00:00
< - EQUALEQUAL
2018-11-14 07:56:26 +00:00
/ EXCLAMATIONMARKEQUAL
/ LARROW
/ RARROW
/ LARROWEQUAL
/ RARROWEQUAL
2018-03-24 23:25:53 +00:00
2018-11-14 07:56:26 +00:00
BitwiseOp
2018-11-17 06:38:35 +00:00
< - AMPERSAND
2018-11-14 07:56:26 +00:00
/ CARET
/ PIPE
/ KEYWORD_orelse
/ KEYWORD_catch Payload?
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
BitShiftOp
2018-11-17 06:38:35 +00:00
< - LARROW2
2018-11-14 07:56:26 +00:00
/ RARROW2
2017-11-07 08:22:27 +00:00
2018-11-14 07:56:26 +00:00
AdditionOp
2018-11-17 06:38:35 +00:00
< - PLUS
2018-11-14 07:56:26 +00:00
/ MINUS
/ PLUS2
/ PLUSPERCENT
/ MINUSPERCENT
MultiplyOp
2018-11-17 06:38:35 +00:00
< - PIPE2
2018-11-14 07:56:26 +00:00
/ ASTERISK
/ SLASH
/ PERCENT
/ ASTERISK2
/ ASTERISKPERCENT
PrefixOp
2018-11-17 06:38:35 +00:00
< - EXCLAMATIONMARK
2018-11-14 07:56:26 +00:00
/ MINUS
/ TILDE
/ MINUSPERCENT
/ AMPERSAND
/ KEYWORD_try
/ KEYWORD_await
PrefixTypeOp
2018-11-17 06:38:35 +00:00
< - QUESTIONMARK
2020-05-15 21:38:40 +01:00
/ KEYWORD_anyframe MINUSRARROW
2019-03-25 16:55:45 +00:00
/ ArrayTypeStart (ByteAlign / KEYWORD_const / KEYWORD_volatile / KEYWORD_allowzero)*
/ PtrTypeStart (KEYWORD_align LPAREN Expr (COLON INTEGER COLON INTEGER)? RPAREN / KEYWORD_const / KEYWORD_volatile / KEYWORD_allowzero)*
2018-11-14 07:56:26 +00:00
SuffixOp
2018-11-17 06:38:35 +00:00
< - LBRACKET Expr (DOT2 Expr?)? RBRACKET
2018-11-14 07:56:26 +00:00
/ DOT IDENTIFIER
/ DOTASTERISK
/ DOTQUESTIONMARK
2018-11-17 13:36:36 +00:00
FnCallArguments < - LPAREN ExprList RPAREN
2018-11-14 07:56:26 +00:00
# Ptr specific
2018-11-17 06:38:35 +00:00
ArrayTypeStart < - LBRACKET Expr? RBRACKET
2018-11-14 07:56:26 +00:00
PtrTypeStart
2018-11-17 06:38:35 +00:00
< - ASTERISK
2018-11-14 07:56:26 +00:00
/ ASTERISK2
2019-02-10 17:02:38 +00:00
/ PTRUNKNOWN
/ PTRC
2018-11-14 07:56:26 +00:00
# ContainerDecl specific
2018-11-17 06:38:35 +00:00
ContainerDeclAuto < - ContainerDeclType LBRACE ContainerMembers RBRACE
2018-11-14 07:56:26 +00:00
ContainerDeclType
2020-09-25 21:12:11 +01:00
< - (KEYWORD_struct / KEYWORD_enum / KEYWORD_opaque) (LPAREN Expr RPAREN)?
2018-11-14 07:56:26 +00:00
/ KEYWORD_union (LPAREN (KEYWORD_enum (LPAREN Expr RPAREN)? / Expr) RPAREN)?
# Alignment
2018-11-17 06:38:35 +00:00
ByteAlign < - KEYWORD_align LPAREN Expr RPAREN
2018-11-14 07:56:26 +00:00
# Lists
2018-11-17 06:38:35 +00:00
IdentifierList < - (IDENTIFIER COMMA)* IDENTIFIER?
2018-11-14 07:56:26 +00:00
2018-11-17 06:38:35 +00:00
SwitchProngList < - (SwitchProng COMMA)* SwitchProng?
2018-11-14 07:56:26 +00:00
2018-11-17 06:38:35 +00:00
AsmOutputList < - (AsmOutputItem COMMA)* AsmOutputItem?
2018-11-14 07:56:26 +00:00
2018-11-17 06:38:35 +00:00
AsmInputList < - (AsmInputItem COMMA)* AsmInputItem?
2018-11-14 07:56:26 +00:00
2018-11-17 06:38:35 +00:00
StringList < - (STRINGLITERAL COMMA)* STRINGLITERAL?
2018-11-14 07:56:26 +00:00
2018-11-17 06:38:35 +00:00
ParamDeclList < - (ParamDecl COMMA)* ParamDecl?
2018-11-14 07:56:26 +00:00
2018-11-17 06:38:35 +00:00
ExprList < - (Expr COMMA)* Expr?
2018-11-14 07:56:26 +00:00
# *** Tokens ***
2018-11-17 06:38:35 +00:00
eof < - !.
hex < - [0-9a-fA-F]
2018-11-14 07:56:26 +00:00
char_escape
2018-11-17 06:38:35 +00:00
< - "\\x" hex hex
2019-07-05 06:52:17 +01:00
/ "\\u{" hex+ "}"
2018-11-14 07:56:26 +00:00
/ "\\" [nr\\t'"]
char_char
2018-11-17 06:38:35 +00:00
< - char_escape
2018-11-14 07:56:26 +00:00
/ [^\\'\n]
string_char
2018-11-17 06:38:35 +00:00
< - char_escape
2018-11-14 07:56:26 +00:00
/ [^\\"\n]
2018-11-17 06:38:35 +00:00
line_comment < - '//'[^\n]*
line_string < - ("\\\\" [^\n]* [ \n]*)+
skip < - ([ \n] / line_comment)*
2018-11-14 07:56:26 +00:00
2018-11-17 06:38:35 +00:00
CHAR_LITERAL < - "'" char_char "'" skip
2018-11-14 07:56:26 +00:00
FLOAT
2019-03-31 12:15:35 +01:00
< - "0x" hex+ "." hex+ ([pP] [-+]? hex+)? skip
2018-11-14 07:56:26 +00:00
/ [0-9]+ "." [0-9]+ ([eE] [-+]? [0-9]+)? skip
/ "0x" hex+ "."? [pP] [-+]? hex+ skip
/ [0-9]+ "."? [eE] [-+]? [0-9]+ skip
INTEGER
2018-11-17 06:38:35 +00:00
< - "0b" [01]+ skip
2018-11-14 07:56:26 +00:00
/ "0o" [0-7]+ skip
/ "0x" hex+ skip
/ [0-9]+ skip
2020-01-14 19:24:39 +00:00
STRINGLITERALSINGLE < - "\"" string_char* "\"" skip
2018-11-14 07:56:26 +00:00
STRINGLITERAL
2020-01-14 19:24:39 +00:00
< - STRINGLITERALSINGLE
2018-11-14 07:56:26 +00:00
/ line_string skip
IDENTIFIER
2020-01-12 08:35:30 +00:00
< - !keyword [A-Za-z_] [A-Za-z0-9_]* skip
2018-11-14 07:56:26 +00:00
/ "@\"" string_char* "\"" skip
2018-11-17 13:36:36 +00:00
BUILTINIDENTIFIER < - "@"[A-Za-z_][A-Za-z0-9_]* skip
2018-11-17 06:38:35 +00:00
AMPERSAND < - '& ' ![=] skip
AMPERSANDEQUAL < - '& =' skip
ASTERISK < - '*' ![*%=] skip
ASTERISK2 < - '**' skip
ASTERISKEQUAL < - '*=' skip
ASTERISKPERCENT < - '*%' ![=] skip
ASTERISKPERCENTEQUAL < - '*%=' skip
CARET < - '^' ![=] skip
CARETEQUAL < - '^=' skip
COLON < - ':' skip
COMMA < - ',' skip
DOT < - '.' ![*.?] skip
DOT2 < - '..' ![.] skip
DOT3 < - '...' skip
DOTASTERISK < - '.*' skip
DOTQUESTIONMARK < - '.?' skip
2018-11-17 13:36:36 +00:00
EQUAL < - '=' ![> =] skip
2018-11-17 06:38:35 +00:00
EQUALEQUAL < - '==' skip
2018-11-17 13:36:36 +00:00
EQUALRARROW < - '=> ' skip
2018-11-17 06:38:35 +00:00
EXCLAMATIONMARK < - '!' ![=] skip
EXCLAMATIONMARKEQUAL < - '!=' skip
LARROW < - '< ' ![< =] skip
LARROW2 < - '< < ' ![=] skip
LARROW2EQUAL < - '< < =' skip
LARROWEQUAL < - '< =' skip
LBRACE < - '{' skip
2019-02-10 17:02:38 +00:00
LBRACKET < - '[' ![*] skip
2018-11-17 06:38:35 +00:00
LPAREN < - '(' skip
2018-11-17 13:36:36 +00:00
MINUS < - '-' ![%=> ] skip
2018-11-17 06:38:35 +00:00
MINUSEQUAL < - '-=' skip
MINUSPERCENT < - '-%' ![=] skip
MINUSPERCENTEQUAL < - '-%=' skip
2018-11-17 13:36:36 +00:00
MINUSRARROW < - '-> ' skip
2018-11-17 06:38:35 +00:00
PERCENT < - '%' ![=] skip
PERCENTEQUAL < - '%=' skip
PIPE < - '|' ![|=] skip
PIPE2 < - '||' skip
PIPEEQUAL < - '|=' skip
PLUS < - '+' ![%+=] skip
PLUS2 < - '++' skip
PLUSEQUAL < - '+=' skip
PLUSPERCENT < - '+%' ![=] skip
PLUSPERCENTEQUAL < - '+%=' skip
2019-02-10 17:02:38 +00:00
PTRC < - '[*c]' skip
PTRUNKNOWN < - '[*]' skip
2018-11-17 06:38:35 +00:00
QUESTIONMARK < - '?' skip
2018-11-17 13:36:36 +00:00
RARROW < - '> ' ![> =] skip
RARROW2 < - '> > ' ![=] skip
RARROW2EQUAL < - '> > =' skip
RARROWEQUAL < - '> =' skip
2018-11-17 06:38:35 +00:00
RBRACE < - '}' skip
RBRACKET < - ']' skip
RPAREN < - ')' skip
SEMICOLON < - ';' skip
SLASH < - '/' ![=] skip
SLASHEQUAL < - '/=' skip
TILDE < - '~' skip
end_of_word < - ![a-zA-Z0-9_] skip
KEYWORD_align < - 'align' end_of_word
2019-03-25 16:55:45 +00:00
KEYWORD_allowzero < - 'allowzero' end_of_word
2018-11-17 06:38:35 +00:00
KEYWORD_and < - 'and' end_of_word
2020-05-15 21:38:40 +01:00
KEYWORD_anyframe < - 'anyframe' end_of_word
2020-07-11 12:08:20 +01:00
KEYWORD_anytype < - 'anytype' end_of_word
2018-11-17 06:38:35 +00:00
KEYWORD_asm < - 'asm' end_of_word
KEYWORD_async < - 'async' end_of_word
KEYWORD_await < - 'await' end_of_word
KEYWORD_break < - 'break' end_of_word
KEYWORD_catch < - 'catch' end_of_word
KEYWORD_comptime < - 'comptime' end_of_word
KEYWORD_const < - 'const' end_of_word
KEYWORD_continue < - 'continue' end_of_word
KEYWORD_defer < - 'defer' end_of_word
KEYWORD_else < - 'else' end_of_word
KEYWORD_enum < - 'enum' end_of_word
KEYWORD_errdefer < - 'errdefer' end_of_word
KEYWORD_error < - 'error' end_of_word
KEYWORD_export < - 'export' end_of_word
KEYWORD_extern < - 'extern' end_of_word
KEYWORD_false < - 'false' end_of_word
KEYWORD_fn < - 'fn' end_of_word
KEYWORD_for < - 'for' end_of_word
KEYWORD_if < - 'if' end_of_word
KEYWORD_inline < - 'inline' end_of_word
KEYWORD_noalias < - 'noalias' end_of_word
2020-05-14 09:19:14 +01:00
KEYWORD_nosuspend < - 'nosuspend' end_of_word
2018-11-17 06:38:35 +00:00
KEYWORD_null < - 'null' end_of_word
2020-09-25 21:12:11 +01:00
KEYWORD_opaque < - 'opaque' end_of_word
2018-11-17 06:38:35 +00:00
KEYWORD_or < - 'or' end_of_word
KEYWORD_orelse < - 'orelse' end_of_word
KEYWORD_packed < - 'packed' end_of_word
KEYWORD_pub < - 'pub' end_of_word
KEYWORD_resume < - 'resume' end_of_word
KEYWORD_return < - 'return' end_of_word
KEYWORD_linksection < - 'linksection' end_of_word
KEYWORD_struct < - 'struct' end_of_word
KEYWORD_suspend < - 'suspend' end_of_word
KEYWORD_switch < - 'switch' end_of_word
KEYWORD_test < - 'test' end_of_word
2019-02-10 01:57:45 +00:00
KEYWORD_threadlocal < - 'threadlocal' end_of_word
2018-11-17 06:38:35 +00:00
KEYWORD_true < - 'true' end_of_word
KEYWORD_try < - 'try' end_of_word
KEYWORD_undefined < - 'undefined' end_of_word
KEYWORD_union < - 'union' end_of_word
KEYWORD_unreachable < - 'unreachable' end_of_word
2019-05-29 22:39:26 +01:00
KEYWORD_usingnamespace < - 'usingnamespace' end_of_word
2018-11-17 06:38:35 +00:00
KEYWORD_var < - 'var' end_of_word
KEYWORD_volatile < - 'volatile' end_of_word
KEYWORD_while < - 'while' end_of_word
2020-07-11 12:08:20 +01:00
keyword < - KEYWORD_align / KEYWORD_and / KEYWORD_anyframe / KEYWORD_anytype
/ KEYWORD_allowzero / KEYWORD_asm / KEYWORD_async / KEYWORD_await / KEYWORD_break
2018-11-14 07:56:26 +00:00
/ KEYWORD_catch / KEYWORD_comptime / KEYWORD_const / KEYWORD_continue
/ KEYWORD_defer / KEYWORD_else / KEYWORD_enum / KEYWORD_errdefer
/ KEYWORD_error / KEYWORD_export / KEYWORD_extern / KEYWORD_false
/ KEYWORD_fn / KEYWORD_for / KEYWORD_if / KEYWORD_inline
2020-09-25 21:12:11 +01:00
/ KEYWORD_noalias / KEYWORD_null / KEYWORD_opaque / KEYWORD_or
2020-07-11 12:08:20 +01:00
/ KEYWORD_orelse / KEYWORD_packed / KEYWORD_pub
2018-11-17 06:38:35 +00:00
/ KEYWORD_resume / KEYWORD_return / KEYWORD_linksection
2020-01-06 23:26:15 +00:00
/ KEYWORD_struct / KEYWORD_suspend
2019-02-10 01:57:45 +00:00
/ KEYWORD_switch / KEYWORD_test / KEYWORD_threadlocal / KEYWORD_true / KEYWORD_try
2018-11-14 07:56:26 +00:00
/ KEYWORD_undefined / KEYWORD_union / KEYWORD_unreachable
2019-05-29 22:39:26 +01:00
/ KEYWORD_usingnamespace / KEYWORD_var / KEYWORD_volatile / KEYWORD_while< / code > < / pre >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Zen#}
2017-11-07 08:22:27 +00:00
< ul >
< li > Communicate intent precisely.< / li >
< li > Edge cases matter.< / li >
< li > Favor reading code over writing code.< / li >
< li > Only one obvious way to do things.< / li >
< li > Runtime crashes are better than bugs.< / li >
< li > Compile errors are better than runtime crashes.< / li >
< li > Incremental improvements.< / li >
< li > Avoid local maximums.< / li >
< li > Reduce the amount one must remember.< / li >
2020-09-15 21:40:01 +01:00
< li > Focus on code rather than style.< / li >
< li > Resource allocation may fail; resource deallocation must succeed.< / li >
< li > Memory is a resource.< / li >
2020-08-31 22:40:08 +01:00
< li > Together we serve the users.< / li >
2017-11-07 08:22:27 +00:00
< / ul >
2018-01-17 04:19:05 +00:00
{#header_close#}
2019-10-23 11:55:20 +01:00
< / div > < / div >
2017-11-07 08:22:27 +00:00
< / div >
< / body >
< / html >