2017-11-07 08:22:27 +00:00
<!doctype html>
< html >
< head >
< meta charset = "utf-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1, user-scalable=no" / >
< title > Documentation - The Zig Programming Language< / title >
2018-01-19 08:03:20 +00:00
< style type = "text/css" >
.hljs{display:block;overflow-x:auto;padding:0.5em;color:#333;background:#f8f8f8}.hljs-comment,.hljs-quote{color:#998;font-style:italic}.hljs-keyword,.hljs-selector-tag,.hljs-subst{color:#333;font-weight:bold}.hljs-number,.hljs-literal,.hljs-variable,.hljs-template-variable,.hljs-tag .hljs-attr{color:#008080}.hljs-string,.hljs-doctag{color:#d14}.hljs-title,.hljs-section,.hljs-selector-id{color:#900;font-weight:bold}.hljs-subst{font-weight:normal}.hljs-type,.hljs-class .hljs-title{color:#458;font-weight:bold}.hljs-tag,.hljs-name,.hljs-attribute{color:#000080;font-weight:normal}.hljs-regexp,.hljs-link{color:#009926}.hljs-symbol,.hljs-bullet{color:#990073}.hljs-built_in,.hljs-builtin-name{color:#0086b3}.hljs-meta{color:#999;font-weight:bold}.hljs-deletion{background:#fdd}.hljs-addition{background:#dfd}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:bold}
< / style >
2017-11-07 08:22:27 +00:00
< style type = "text/css" >
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;
}
2018-01-23 04:06:07 +00:00
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;
}
.table-wrapper {
width: 100%;
overflow-y: auto;
}
/* Desktop */
@media screen and (min-width: 56.25em) {
2017-11-07 08:22:27 +00:00
#nav {
width: 20em;
height: 100%;
position: fixed;
2018-01-30 04:33:38 +00:00
overflow-y: scroll;
2017-11-07 08:22:27 +00:00
left: 0;
top: 0;
2018-01-30 04:33:38 +00:00
padding-left: 1em;
2017-11-07 08:22:27 +00:00
}
#contents {
2018-01-30 04:33:38 +00:00
max-width: 60em;
2017-11-07 08:22:27 +00:00
padding-left: 22em;
2018-01-30 04:33:38 +00:00
padding: 1em;
padding-left: 24em;
}
}
/* Mobile */
@media screen and (max-width: 56.25em) {
body, code {
font-size: small;
}
#nav {
border-bottom: 1px solid grey;
2017-11-07 08:22:27 +00:00
}
}
< / style >
< / head >
< body >
< div id = "nav" >
2018-01-30 04:33:38 +00:00
< h3 > Index< / h3 >
{#nav#}
2017-11-07 08:22:27 +00:00
< / div >
< div id = "contents" >
2018-01-17 04:19:05 +00:00
{#header_open|Introduction#}
2017-11-07 08:22:27 +00:00
< p >
Zig is an open-source programming language designed for < strong > robustness< / strong > ,
< strong > optimality< / strong > , and < strong > clarity< / strong > .
< / 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 >
< li > < strong > Clear< / strong > - precisely communicate your intent to the compiler and other programmers. The language imposes a low overhead to reading code.< / li >
< / 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 01:27:44 +00: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.
This HTML document depends on no external files, so you can use it offline.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#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 {
2017-11-07 08:22:27 +00:00
// If this program is run without stdout attached, exit with an error.
2018-01-07 21:51:46 +00:00
var stdout_file = try std.io.getStdOut();
2017-11-07 08:22:27 +00:00
// If this program encounters pipe failure when printing to stdout, exit
// with an error.
2018-01-07 21:51:46 +00:00
try stdout_file.write("Hello, world!\n");
2018-01-17 06:50:35 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
Usually you don't want to write to stdout. You want to write to stderr. And you
don't care if it fails. It's more like a < em > warning message< / em > that you want
to emit. For that you can use a simpler API:
< / p >
2018-01-17 06:50:35 +00:00
{#code_begin|exe|hello#}
const warn = @import("std").debug.warn;
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
warn("Hello, world!\n");
2018-01-17 06:50:35 +00:00
}
{#code_end#}
2018-01-23 04:06:07 +00:00
< p >
2018-02-08 08:02:41 +00:00
Note that we also left off the < code class = "zig" > !< / code > from the return type.
In Zig, if your main function cannot fail, you must use the < code class = "zig" > void< / code > return type.
2018-01-23 04:06:07 +00:00
< / p >
2018-01-17 05:22:33 +00:00
{#see_also|Values|@import|Errors|Root Source File#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-07-31 02:27:07 +00: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 >
There are no multiline comments in Zig (e.g. like < code > /* */< / code >
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.
< code class = "zig" > ///< / code > but not < code class = "zig" > ////< / code > );
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).
const Timestamp = struct {
/// The number of seconds since the epoch (this is also a doc comment).
seconds: i64, // signed so we can represent pre-1970 (not a doc comment)
/// The number of nanoseconds past the second (doc comment again).
nanos: u32,
/// Returns a `Timestamp` struct representing the Unix epoch; that is, the
/// moment of 1970 Jan 1 00:00:00 UTC (this is a doc comment too).
pub fn unixEpoch() Timestamp {
return Timestamp{
.seconds = 0,
.nanos = 0,
};
}
};
{#code_end#}
< p >
Doc comments are only allowed in certain places; eventually, it will
become a compile error have a doc comment in an unexpected place, such as
in the middle of an expression, or just before a non-doc comment.
< / p >
{#header_close#}
{#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#}
const std = @import("std");
const warn = std.debug.warn;
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;
warn("1 + 1 = {}\n", one_plus_one);
// floats
const seven_div_three: f32 = 7.0 / 3.0;
warn("7.0 / 3.0 = {}\n", seven_div_three);
// boolean
warn("{}\n{}\n{}\n",
true and false,
true or false,
!true);
2018-06-10 03:42:14 +00:00
// optional
var optional_value: ?[]const u8 = null;
assert(optional_value == null);
2017-11-07 08:22:27 +00:00
2018-06-10 03:42:14 +00:00
warn("\noptional 1\ntype: {}\nvalue: {}\n",
@typeName(@typeOf(optional_value)), optional_value);
2017-11-07 08:22:27 +00:00
2018-06-10 03:42:14 +00:00
optional_value = "hi";
assert(optional_value != null);
2017-11-07 08:22:27 +00:00
2018-06-10 03:42:14 +00:00
warn("\noptional 2\ntype: {}\nvalue: {}\n",
@typeName(@typeOf(optional_value)), optional_value);
2017-11-07 08:22:27 +00:00
// error union
2018-02-08 08:02:41 +00:00
var number_or_error: error!i32 = error.ArgNotFound;
2017-11-07 08:22:27 +00:00
warn("\nerror union 1\ntype: {}\nvalue: {}\n",
@typeName(@typeOf(number_or_error)), number_or_error);
number_or_error = 1234;
warn("\nerror union 2\ntype: {}\nvalue: {}\n",
@typeName(@typeOf(number_or_error)), 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 >
< td > < code > i2< / code > < / td >
< td > < code > (none)< / code > < / td >
< td > signed 2-bit integer< / td >
< / tr >
< tr >
< td > < code > u2< / code > < / td >
< td > < code > (none)< / code > < / td >
< td > unsigned 2-bit integer< / td >
< / tr >
< tr >
< td > < code > i3< / code > < / td >
< td > < code > (none)< / code > < / td >
< td > signed 3-bit integer< / td >
< / tr >
< tr >
< td > < code > u3< / code > < / td >
< td > < code > (none)< / code > < / td >
< td > unsigned 3-bit integer< / td >
< / tr >
< tr >
< td > < code > i4< / code > < / td >
< td > < code > (none)< / code > < / td >
< td > signed 4-bit integer< / td >
< / tr >
< tr >
< td > < code > u4< / code > < / td >
< td > < code > (none)< / code > < / td >
< td > unsigned 4-bit integer< / td >
< / tr >
< tr >
< td > < code > i5< / code > < / td >
< td > < code > (none)< / code > < / td >
< td > signed 5-bit integer< / td >
< / tr >
< tr >
< td > < code > u5< / code > < / td >
< td > < code > (none)< / code > < / td >
< td > unsigned 5-bit integer< / td >
< / tr >
< tr >
< td > < code > i6< / code > < / td >
< td > < code > (none)< / code > < / td >
< td > signed 6-bit integer< / td >
< / tr >
< tr >
< td > < code > u6< / code > < / td >
< td > < code > (none)< / code > < / td >
< td > unsigned 6-bit integer< / td >
< / tr >
< tr >
< td > < code > i7< / code > < / td >
< td > < code > (none)< / code > < / td >
< td > signed 7-bit integer< / td >
< / tr >
< tr >
< td > < code > u7< / code > < / td >
< td > < code > (none)< / code > < / td >
< td > unsigned 7-bit integer< / td >
< / tr >
< tr >
< td > < code > i8< / code > < / td >
< td > < code > int8_t< / code > < / td >
< td > signed 8-bit integer< / td >
< / tr >
< tr >
< td > < code > u8< / code > < / td >
< td > < code > uint8_t< / code > < / td >
< td > unsigned 8-bit integer< / td >
< / tr >
< tr >
< td > < code > i16< / code > < / td >
< td > < code > int16_t< / code > < / td >
< td > signed 16-bit integer< / td >
< / tr >
< tr >
< td > < code > u16< / code > < / td >
< td > < code > uint16_t< / code > < / td >
< td > unsigned 16-bit integer< / td >
< / tr >
< tr >
< td > < code > i32< / code > < / td >
< td > < code > int32_t< / code > < / td >
< td > signed 32-bit integer< / td >
< / tr >
< tr >
< td > < code > u32< / code > < / td >
< td > < code > uint32_t< / code > < / td >
< td > unsigned 32-bit integer< / td >
< / tr >
< tr >
< td > < code > i64< / code > < / td >
< td > < code > int64_t< / code > < / td >
< td > signed 64-bit integer< / td >
< / tr >
< tr >
< td > < code > u64< / code > < / td >
< td > < code > uint64_t< / code > < / td >
< td > unsigned 64-bit integer< / td >
< / tr >
< tr >
< td > < code > i128< / code > < / td >
< td > < code > __int128< / code > < / td >
< td > signed 128-bit integer< / td >
< / tr >
< tr >
< td > < code > u128< / code > < / td >
< td > < code > unsigned __int128< / code > < / td >
< td > unsigned 128-bit integer< / td >
< / tr >
< tr >
< td > < code > isize< / code > < / td >
< td > < code > intptr_t< / code > < / td >
< td > signed pointer sized integer< / td >
< / tr >
< tr >
< td > < code > usize< / code > < / td >
< td > < code > uintptr_t< / code > < / td >
< td > unsigned pointer sized integer< / td >
< / tr >
< tr >
< td > < code > c_short< / code > < / td >
< td > < code > short< / code > < / td >
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
< td > < code > c_ushort< / code > < / td >
< td > < code > unsigned short< / code > < / td >
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
< td > < code > c_int< / code > < / td >
< td > < code > int< / code > < / td >
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
< td > < code > c_uint< / code > < / td >
< td > < code > unsigned int< / code > < / td >
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
< td > < code > c_long< / code > < / td >
< td > < code > long< / code > < / td >
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
< td > < code > c_ulong< / code > < / td >
< td > < code > unsigned long< / code > < / td >
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
< td > < code > c_longlong< / code > < / td >
< td > < code > long long< / code > < / td >
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
< td > < code > c_ulonglong< / code > < / td >
< td > < code > unsigned long long< / code > < / td >
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
< td > < code > c_longdouble< / code > < / td >
< td > < code > long double< / code > < / td >
< td > for ABI compatibility with C< / td >
< / tr >
< tr >
< td > < code > c_void< / code > < / td >
< td > < code > void< / code > < / td >
< td > for ABI compatibility with C< / td >
< / tr >
2018-06-27 16:59:12 +00:00
< tr >
< td > < code > f16< / code > < / td >
< td > < code > float< / code > < / td >
< td > 16-bit floating point (10-bit mantissa) IEEE-754-2008 binary16< / td >
< / tr >
2017-11-07 08:22:27 +00:00
< tr >
< td > < code > f32< / code > < / td >
< td > < code > float< / code > < / td >
2018-06-16 23:53:52 +00:00
< td > 32-bit floating point (23-bit mantissa) IEEE-754-2008 binary32< / td >
2017-11-07 08:22:27 +00:00
< / tr >
< tr >
< td > < code > f64< / code > < / td >
< td > < code > double< / code > < / td >
2018-06-16 23:53:52 +00:00
< td > 64-bit floating point (52-bit mantissa) IEEE-754-2008 binary64< / td >
2017-11-07 08:22:27 +00:00
< / tr >
< tr >
< td > < code > f128< / code > < / td >
< td > (none)< / td >
2018-06-16 23:53:52 +00:00
< td > 128-bit floating point (112-bit mantissa) IEEE-754-2008 binary128< / td >
2017-11-07 08:22:27 +00:00
< / tr >
< tr >
< td > < code > bool< / code > < / td >
< td > < code > bool< / code > < / td >
< td > < code > true< / code > or < code > false< / code > < / td >
< / tr >
< tr >
< td > < code > void< / code > < / td >
< td > (none)< / td >
< td > 0 bit type< / td >
< / tr >
< tr >
< td > < code > noreturn< / code > < / td >
< td > (none)< / td >
2018-01-24 04:12:38 +00:00
< td > the type of < code > break< / code > , < code > continue< / code > , < code > return< / code > , < code > unreachable< / code > , and < code > while (true) {}< / code > < / td >
2017-11-07 08:22:27 +00:00
< / tr >
< tr >
< td > < code > type< / code > < / td >
< td > (none)< / td >
< td > the type of types< / td >
< / tr >
< tr >
< td > < code > error< / code > < / td >
< td > (none)< / td >
< td > an error code< / td >
< / tr >
2018-06-16 23:53:52 +00:00
< tr >
< td > < code > comptime_int< / code > < / td >
< td > (none)< / td >
< td > Only allowed for {#link|comptime#}-known values. The type of integer literals.< / td >
< / tr >
< tr >
< td > < code > comptime_float< / code > < / td >
< 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-01-17 05:22:33 +00:00
{#see_also|Integers|Floats|void|Errors#}
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 >
< td > < code > true< / code > and < code > false< / code > < / td >
< td > < code > bool< / code > values< / td >
< / tr >
< tr >
< td > < code > null< / code > < / td >
2018-06-10 03:42:14 +00:00
< td > used to set an optional type to < code > null< / code > < / td >
2017-11-07 08:22:27 +00:00
< / tr >
< tr >
< td > < code > undefined< / code > < / td >
< td > used to leave a value unspecified< / td >
< / tr >
< tr >
< td > < code > this< / code > < / td >
< td > refers to the thing in immediate scope< / td >
< / tr >
< / table >
2018-01-30 04:33:38 +00:00
< / div >
2018-06-10 03:42:14 +00:00
{#see_also|Optionals|this#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|String Literals#}
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" {
// In Zig a string literal is an array of bytes.
const normal_bytes = "hello";
assert(@typeOf(normal_bytes) == [5]u8);
assert(normal_bytes.len == 5);
assert(normal_bytes[1] == 'e');
assert('e' == '\x65');
assert(mem.eql(u8, "hello", "h\x65llo"));
// A C string literal is a null terminated pointer.
const null_terminated_bytes = c"hello";
2018-06-04 05:09:15 +00:00
assert(@typeOf(null_terminated_bytes) == [*]const u8);
2017-11-07 08:22:27 +00:00
assert(null_terminated_bytes[5] == 0);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-01-17 05:22:33 +00:00
{#see_also|Arrays|Zig Test#}
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 >
< td > < code > \n< / code > < / td >
< td > Newline< / td >
< / tr >
< tr >
< td > < code > \r< / code > < / td >
< td > Carriage Return< / td >
< / tr >
< tr >
< td > < code > \t< / code > < / td >
< td > Tab< / td >
< / tr >
< tr >
< td > < code > \\< / code > < / td >
< td > Backslash< / td >
< / tr >
< tr >
< td > < code > \'< / code > < / td >
< td > Single Quote< / td >
< / tr >
< tr >
< td > < code > \"< / code > < / td >
< td > Double Quote< / td >
< / tr >
< tr >
< td > < code > \xNN< / code > < / td >
< td > hexadecimal 8-bit character code (2 digits)< / td >
< / tr >
< tr >
< td > < code > \uNNNN< / code > < / td >
< td > hexadecimal 16-bit Unicode character code UTF-8 encoded (4 digits)< / td >
< / tr >
< tr >
< td > < code > \UNNNNNN< / code > < / td >
< td > hexadecimal 24-bit Unicode character code UTF-8 encoded (6 digits)< / td >
< / tr >
< / table >
2018-01-30 04:33:38 +00:00
< / div >
2017-11-07 08:22:27 +00:00
< p > Note that the maximum valid Unicode point is < code > 0x10ffff< / code > .< / 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.
To start a multiline string literal, use the < code > \\< / code > token. Just like a comment,
the string literal goes until the end of the line. The end of the line is
not included in the string literal.
However, if the next line begins with < code > \\< / code > then a newline is appended and
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#}
2017-11-07 08:22:27 +00:00
< p >
For a multiline C string literal, prepend < code > c< / code > to each < code > \\< / code > :
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
const c_string_literal =
c\\#include < stdio.h >
2017-11-07 08:22:27 +00:00
c\\
c\\int main(int argc, char **argv) {
c\\ printf("hello world\n");
c\\ return 0;
c\\}
2018-01-19 08:03:20 +00:00
;
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-06-04 05:09:15 +00:00
In this example the variable < code > c_string_literal< / code > has type < code > [*]const char< / code > and
2017-11-07 08:22:27 +00:00
has a terminating null byte.
< / p >
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#}
2017-11-07 08:22:27 +00:00
< p > Use < code > const< / code > 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#}
2017-11-07 08:22:27 +00:00
< p > If you need a variable that you can modify, use < code > var< / code > :< / 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 22:12:05 +00:00
{#header_open|undefined#}
2017-11-07 08:22:27 +00:00
< p > Use < code > undefined< / code > 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 18:03:27 +00:00
< p >
< code > undefined< / code > can be {#link|implicitly cast|Implicit Casts#} to any type.
Once this happens, it is no longer possible to detect that the value is < code > undefined< / code > .
< code > undefined< / code > means the value could be anything, even something that is nonsense
according to the type. Translated into English, < code > undefined< / code > means "Not a meaningful
value. Using this value would be a bug. The value will be unused, or overwritten before being used."
< / p >
< p >
In {#link|Debug#} mode, Zig writes < code > 0xaa< / code > bytes to undefined memory. This is to catch
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 22:12:05 +00:00
{#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;
{#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 >
In this function, values < code > a< / code > and < code > b< / code > are known only at runtime,
and thus this division operation is vulnerable to both integer overflow and
division by zero.
< / p >
< p >
Operators such as < code > +< / code > and < code > -< / code > cause undefined behavior on
integer overflow. Also available are operations such as < code > +%< / code > and
< code > -%< / code > which are defined to have wrapping arithmetic on all targets.
< / p >
2018-01-17 05:22:33 +00:00
{#see_also|Integer Overflow|Division by Zero|Wrapping Operations#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_close#}
{#header_open|Floats#}
2018-06-16 23:53:52 +00:00
< p > Zig has the following floating point types:< / p >
< ul >
2018-06-27 16:59:12 +00:00
< li > < code > f16< / code > - IEEE-754-2008 binary16< / li >
2018-06-16 23:53:52 +00:00
< li > < code > f32< / code > - IEEE-754-2008 binary32< / li >
< li > < code > f64< / code > - IEEE-754-2008 binary64< / li >
< li > < code > f128< / code > - IEEE-754-2008 binary128< / li >
< li > < code > c_longdouble< / code > - matches < code > long double< / code > for the target C ABI< / li >
< / ul >
2018-01-17 04:19:05 +00:00
{#header_open|Float Literals#}
2018-06-16 23:53:52 +00:00
< p >
Float literals have type < code > comptime_float< / code > which is guaranteed to hold at least all possible values
2018-07-06 20:20:31 +00:00
that the largest other floating point type can hold. Float literals {#link|implicitly cast|Implicit Casts#} to any other type.
2018-06-16 23:53:52 +00: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;
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Floating Point Operations#}
2017-11-07 08:22:27 +00:00
< p > By default floating point operations use < code > Optimized< / code > mode,
but you can switch to < code > Strict< / code > mode on a per-block basis:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|obj|foo#}
{#code_release_fast#}
const builtin = @import("builtin");
const big = 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
@setFloatMode(this, builtin.FloatMode.Strict);
return x + big - big;
}
2018-01-25 09:10:11 +00:00
export fn foo_optimized(x: f64) f64 {
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#}
const warn = @import("std").debug.warn;
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;
warn("optimized = {}\n", foo_optimized(x));
warn("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#}
{#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 >
< td > < pre > < code class = "zig" > a + b
a += b< / code > < / pre > < / td >
< 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 >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
< pre > < code class = "zig" > 2 + 5 == 7< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a +% b
a +%= b< / code > < / pre > < / td >
< 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 >
< / ul >
< / td >
< td >
< pre > < code class = "zig" > u32(@maxValue(u32)) +% 1 == 0< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a - b
a -= b< / code > < / pre > < / td >
< 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 >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
< pre > < code class = "zig" > 2 - 5 == -3< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a -% b
a -%= b< / code > < / pre > < / td >
< 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 >
< / ul >
< / td >
< td >
< pre > < code class = "zig" > u32(0) -% 1 == @maxValue(u32)< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > -a< code > < / pre > < / td >
< 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 >
< pre > < code class = "zig" > -1 == 0 - 1< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > -%a< code > < / pre > < / td >
< 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 >
< pre > < code class = "zig" > -%i32(@minValue(i32)) == @minValue(i32)< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a * b
a *= b< / code > < / pre > < / td >
< 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 >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
< pre > < code class = "zig" > 2 * 5 == 10< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a *% b
a *%= b< / code > < / pre > < / td >
< 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 >
< / ul >
< / td >
< td >
< pre > < code class = "zig" > u8(200) *% 2 == 144< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a / b
a /= b< / code > < / pre > < / td >
< 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 > Divison.
< 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
{#link|@divExact#} instead of < code > /< / code > .
2017-11-07 08:22:27 +00:00
< / li >
< / ul >
< / td >
< td >
< pre > < code class = "zig" > 10 / 5 == 2< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a % b
a %= b< / code > < / pre > < / td >
< 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
{#link|@mod#} instead of < code > %< / code > .
2017-11-07 08:22:27 +00:00
< / li >
< / ul >
< / td >
< td >
< pre > < code class = "zig" > 10 % 3 == 1< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a < < b
a < < = b< / code > < / pre > < / td >
< 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-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 >
< pre > < code class = "zig" > 1 < < 8 == 256< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a > > b
a > > = b< / code > < / pre > < / td >
< 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-01-23 04:06:07 +00:00
< li > See also {#link|@shrExact#}.< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
< pre > < code class = "zig" > 10 > > 1 == 5< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a & b
a & = b< / code > < / pre > < / td >
< 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.
< / td >
< td >
< pre > < code class = "zig" > 0b011 & 0b101 == 0b001< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a | b
a |= b< / code > < / pre > < / td >
< 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.
< / td >
< td >
< pre > < code class = "zig" > 0b010 | 0b100 == 0b110< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a ^ b
a ^= b< / code > < / pre > < / td >
< 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.
< / td >
< td >
< pre > < code class = "zig" > 0b011 ^ 0b101 == 0b110< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > ~a< code > < / pre > < / td >
< 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 >
< pre > < code class = "zig" > ~u8(0b0101111) == 0b1010000< / code > < / pre >
< / td >
< / tr >
< tr >
2018-06-10 05:13:51 +00:00
< td > < pre > < code class = "zig" > a orelse b< / code > < / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-06-10 03:42:14 +00:00
< li > {#link|Optionals#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td > If < code > a< / code > is < code > null< / code > ,
returns < code > b< / code > ("default value"),
otherwise returns the unwrapped value of < code > a< / code > .
2018-01-23 04:06:07 +00:00
Note that < code > b< / code > may be a value of type {#link|noreturn#}.
2017-11-07 08:22:27 +00:00
< / td >
< td >
< pre > < code class = "zig" > const value: ?u32 = null;
2018-06-10 05:13:51 +00:00
const unwrapped = value orelse 1234;
2017-11-07 08:22:27 +00:00
unwrapped == 1234< / code > < / pre >
< / td >
< / tr >
< tr >
2018-06-10 03:42:14 +00:00
< td > < pre > < code class = "zig" > a.?< / code > < / pre > < / td >
2017-11-07 08:22:27 +00:00
< td >
< ul >
2018-06-10 03:42:14 +00:00
< li > {#link|Optionals#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
Equivalent to:
2018-06-10 05:13:51 +00:00
< pre > < code class = "zig" > a orelse unreachable< / code > < / pre >
2017-11-07 08:22:27 +00:00
< / td >
< td >
< pre > < code class = "zig" > const value: ?u32 = 5678;
2018-06-10 03:42:14 +00:00
value.? == 5678< / code > < / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
2018-01-07 22:28:20 +00:00
< td > < pre > < code class = "zig" > a catch b
a catch |err| b< / code > < / 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 >
< td > If < code > a< / code > is an < code > error< / code > ,
returns < code > b< / code > ("default value"),
otherwise returns the unwrapped value of < code > a< / code > .
2018-01-23 04:06:07 +00:00
Note that < code > b< / code > may be a value of type {#link|noreturn#}.
2017-11-07 08:22:27 +00:00
< code > err< / code > is the < code > error< / code > and is in scope of the expression < code > b< / code > .
< / td >
< td >
2018-02-08 08:02:41 +00:00
< pre > < code class = "zig" > const value: error!u32 = error.Broken;
2018-01-07 22:28:20 +00:00
const unwrapped = value catch 1234;
2017-11-07 08:22:27 +00:00
unwrapped == 1234< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a and b< code > < / pre > < / td >
< 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 >
If < code > a< / code > is < code > false< / code > , returns < code > false< / code >
2018-07-18 01:18:41 +00:00
without evaluating < code > b< / code > . Otherwise, returns < code > b< / code > .
2017-11-07 08:22:27 +00:00
< / td >
< td >
< pre > < code class = "zig" > false and true == false< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a or b< code > < / pre > < / td >
< 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 >
If < code > a< / code > is < code > true< / code > , returns < code > true< / code >
2018-07-18 01:18:41 +00:00
without evaluating < code > b< / code > . Otherwise, returns < code > b< / code > .
2017-11-07 08:22:27 +00:00
< / td >
< td >
< pre > < code class = "zig" > false or true == true< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > !a< code > < / pre > < / td >
< 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 >
< pre > < code class = "zig" > !false == true< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a == b< code > < / pre > < / td >
< 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 >
Returns < code > true< / code > if a and b are equal, otherwise returns < code > false< / code > .
< / td >
< td >
< pre > < code class = "zig" > (1 == 1) == true< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a == null< code > < / pre > < / td >
< td >
< ul >
2018-06-10 03:42:14 +00:00
< li > {#link|Optionals#}< / li >
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
Returns < code > true< / code > if a is < code > null< / code > , otherwise returns < code > false< / code > .
< / td >
< td >
< pre > < code class = "zig" > const value: ?u32 = null;
value == null< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a != b< code > < / pre > < / td >
< 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 >
Returns < code > false< / code > if a and b are equal, otherwise returns < code > true< / code > .
< / td >
< td >
< pre > < code class = "zig" > (1 != 1) == false< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a > b< code > < / pre > < / td >
< 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 >
Returns < code > true< / code > if a is greater than b, otherwise returns < code > false< / code > .
< / td >
< td >
< pre > < code class = "zig" > (2 > 1) == true< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a > = b< code > < / pre > < / td >
< 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 >
Returns < code > true< / code > if a is greater than or equal to b, otherwise returns < code > false< / code > .
< / td >
< td >
< pre > < code class = "zig" > (2 > = 1) == true< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a < b< code > < / pre > < / td >
< 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 >
Returns < code > true< / code > if a is less than b, otherwise returns < code > false< / code > .
< / td >
< td >
< pre > < code class = "zig" > (1 < 2) == true< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a < = b< code > < / pre > < / td >
< 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 >
Returns < code > true< / code > if a is less than or equal to b, otherwise returns < code > false< / code > .
< / td >
< td >
< pre > < code class = "zig" > (1 < = 2) == true< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a ++ b< code > < / pre > < / td >
< 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-01-23 04:06:07 +00:00
< li > Only available when < code > a< / code > and < code > b< / code > are {#link|compile-time known|comptime#}.
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
< pre > < code class = "zig" > const mem = @import("std").mem;
const array1 = []u32{1,2};
const array2 = []u32{3,4};
const together = array1 ++ array2;
mem.eql(u32, together, []u32{1,2,3,4})< / code > < / pre >
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > a ** b< code > < / pre > < / td >
< 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-01-23 04:06:07 +00:00
< li > Only available when < code > a< / code > and < code > b< / code > are {#link|compile-time known|comptime#}.
2017-11-07 08:22:27 +00:00
< / ul >
< / td >
< td >
< pre > < code class = "zig" > const mem = @import("std").mem;
const pattern = "ab" ** 3;
mem.eql(u8, pattern, "ababab")< / code > < / pre >
< / td >
< / tr >
< tr >
2018-05-18 03:21:44 +00:00
< td > < pre > < code class = "zig" > a.*< code > < / 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 >
< pre > < code class = "zig" > const x: u32 = 1234;
const ptr = & x;
2018-05-18 03:21:44 +00:00
x.* == 1234< / code > < / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
< tr >
< td > < pre > < code class = "zig" > & a< code > < / pre > < / td >
< td >
All types
< / td >
< td >
Address of.
< / td >
< td >
< pre > < code class = "zig" > const x: u32 = 1234;
const ptr = & x;
2018-05-18 03:21:44 +00:00
x.* == 1234< / code > < / pre >
2017-11-07 08:22:27 +00:00
< / td >
< / tr >
2018-06-13 15:09:41 +00:00
< tr >
< td > < pre > < code class = "zig" > a || b< code > < / pre > < / td >
< td >
< ul >
< li > {#link|Error Set Type#}< / li >
< / ul >
< / td >
< td >
{#link|Merging Error Sets#}
< / td >
< td >
< pre > < code class = "zig" > const A = error{One};
const B = error{Two};
(A || B) == error{One, Two}< / code > < / pre >
< / 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#}
2017-11-07 08:22:27 +00:00
< pre > < code > x() x[] x.y
2018-02-08 08:02:41 +00:00
a!b
2018-06-10 03:42:14 +00:00
!x -x -%x ~x & x ?x
x{} x.* x.?
2018-06-13 15:09:41 +00:00
! * / % ** *% ||
2017-11-07 08:22:27 +00:00
+ - ++ +% -%
< < > >
&
^
|
== != < > < = > =
and
or
2018-06-10 05:13:51 +00:00
orelse catch
2017-11-07 08:22:27 +00:00
= *= /= %= += -= < < = > > = & = ^= |=< / code > < / 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
2018-06-04 05:09:15 +00: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);
}
// a string literal is an array literal
const same_message = "hello";
comptime {
assert(mem.eql(u8, message, same_message));
assert(@typeOf(message) == @typeOf(same_message));
}
test "iterate over an array" {
var sum: usize = 0;
for (message) |byte| {
sum += byte;
}
assert(sum == usize('h') + usize('e') + usize('l') * 2 + usize('o'));
}
// modifiable array
var some_integers: [100]i32 = undefined;
test "modify an array" {
for (some_integers) |*item, i| {
2018-06-17 06:57:07 +00: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
2018-06-04 05:09:15 +00: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 {
2018-06-04 05:09:15 +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
const all_zero = []u16{0} ** 10;
comptime {
assert(all_zero.len == 10);
assert(all_zero[5] == 0);
}
// use compile-time code to initialize an array
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-06-04 05:09:15 +00:00
pt.* = Point{
2018-06-17 06:57:07 +00: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
};
const Point = struct {
x: i32,
y: i32,
};
test "compile-time array initalization" {
assert(fancy_array[4].x == 4);
assert(fancy_array[4].y == 8);
}
// call a function to initialize an array
var more_points = []Point{makePoint(3)} ** 10;
2018-01-25 09:10:11 +00:00
fn makePoint(x: i32) Point {
2018-06-04 05:09:15 +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
}
{#code_end#}
2018-01-17 05:22:33 +00:00
{#see_also|for|Slices#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Pointers#}
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 "address of syntax" {
// Get the address of a variable:
const x: i32 = 1234;
const x_ptr = &x;
// Deference a pointer:
2018-05-18 03:21:44 +00:00
assert(x_ptr.* == 1234);
2017-11-07 08:22:27 +00:00
// When you get the address of a const variable, you get a const pointer.
2018-05-31 14:56:59 +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;
2018-05-31 14:56:59 +00:00
assert(@typeOf(y_ptr) == *i32);
2018-05-18 03:21:44 +00:00
y_ptr.* += 1;
assert(y_ptr.* == 5679);
2017-11-07 08:22:27 +00:00
}
test "pointer array access" {
2018-06-04 05:09:15 +00:00
// Taking an address of an individual element gives a
// pointer to a single item. This kind of pointer
// does not support pointer arithmetic.
2018-06-18 21:25:29 +00:00
var array = []u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
2018-06-04 05:09:15 +00:00
const ptr = &array[2];
assert(@typeOf(ptr) == *u8);
2017-11-07 08:22:27 +00:00
assert(array[2] == 3);
2018-06-04 05:09:15 +00:00
ptr.* += 1;
2017-11-07 08:22:27 +00:00
assert(array[2] == 4);
}
test "pointer slicing" {
2018-07-18 01:18:41 +00:00
// In Zig, we prefer slices over pointers to null-terminated arrays.
2018-06-04 05:09:15 +00:00
// You can turn an array into a slice using slice syntax:
2018-06-18 21:25:29 +00:00
var array = []u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
2018-06-04 05:09:15 +00:00
const slice = array[2..4];
2017-11-07 08:22:27 +00:00
assert(slice.len == 2);
// Slices have bounds checking and are therefore protected
// against this kind of undefined behavior. This is one reason
// we prefer slices to pointers.
assert(array[3] == 4);
slice[1] += 1;
assert(array[3] == 5);
}
comptime {
// Pointers work at compile-time too, as long as you don't use
// @ptrCast.
var x: i32 = 1;
2018-01-19 08:03:20 +00:00
const ptr = &x;
2018-05-18 03:21:44 +00:00
ptr.* += 1;
2017-11-07 08:22:27 +00:00
x += 1;
2018-05-18 03:21:44 +00:00
assert(ptr.* == 3);
2017-11-07 08:22:27 +00:00
}
test "@ptrToInt and @intToPtr" {
// To convert an integer address into a pointer, use @intToPtr:
2018-05-31 14:56:59 +00:00
const ptr = @intToPtr(*i32, 0xdeadbeef);
2017-11-07 08:22:27 +00:00
// To convert a pointer to an integer, use @ptrToInt:
const addr = @ptrToInt(ptr);
assert(@typeOf(addr) == usize);
assert(addr == 0xdeadbeef);
}
comptime {
// Zig is able to do this at compile-time, as long as
// ptr is never dereferenced.
2018-05-31 14:56:59 +00:00
const ptr = @intToPtr(*i32, 0xdeadbeef);
2017-11-07 08:22:27 +00:00
const addr = @ptrToInt(ptr);
assert(@typeOf(addr) == usize);
assert(addr == 0xdeadbeef);
}
test "volatile" {
// In Zig, 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 `volatile`:
2018-05-31 14:56:59 +00:00
const mmio_ptr = @intToPtr(*volatile u8, 0x12345678);
2017-11-07 08:22:27 +00:00
// Now loads and stores with mmio_ptr are guaranteed to all happen
// and in the same order as in source code.
2018-05-31 14:56:59 +00:00
assert(@typeOf(mmio_ptr) == *volatile u8);
2017-11-07 08:22:27 +00:00
}
2018-06-10 03:42:14 +00:00
test "optional pointers" {
// Pointers cannot be null. If you want a null pointer, use the optional
// prefix `?` to make the pointer type optional.
2018-05-31 14:56:59 +00:00
var ptr: ?*i32 = null;
2017-11-07 08:22:27 +00:00
var x: i32 = 1;
2018-01-19 08:03:20 +00:00
ptr = &x;
2017-11-07 08:22:27 +00:00
2018-06-10 03:42:14 +00:00
assert(ptr.?.* == 1);
2017-11-07 08:22:27 +00:00
2018-06-10 03:42:14 +00:00
// Optional pointers are the same size as normal pointers, because pointer
2017-11-07 08:22:27 +00:00
// value 0 is used as the null value.
2018-05-31 14:56:59 +00:00
assert(@sizeOf(?*i32) == @sizeOf(*i32));
2017-11-07 08:22:27 +00:00
}
test "pointer casting" {
// To convert one pointer type to another, use @ptrCast. This is an unsafe
// operation that Zig cannot protect you against. Use @ptrCast only when other
// conversions are not possible.
2018-06-18 21:25:29 +00:00
const bytes align(@alignOf(u32)) = []u8{ 0x12, 0x12, 0x12, 0x12 };
2018-05-31 14:56:59 +00:00
const u32_ptr = @ptrCast(*const u32, &bytes[0]);
2018-05-18 03:21:44 +00: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:
2018-06-18 21:25:29 +00:00
const u32_value = @bytesToSlice(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.
2018-05-31 14:56:59 +00:00
assert((*u32).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
less than < code > 1 < < 29< / code > .
< / 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#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
const builtin = @import("builtin");
test "variable alignment" {
var x: i32 = 1234;
const align_of_i32 = @alignOf(@typeOf(x));
2018-05-31 14:56:59 +00:00
assert(@typeOf(& x) == *i32);
assert(*i32 == *align(align_of_i32) i32);
2017-11-07 08:22:27 +00:00
if (builtin.arch == builtin.Arch.x86_64) {
2018-05-31 14:56:59 +00:00
assert((*i32).alignment == 4);
2017-11-07 08:22:27 +00:00
}
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-06 20:20:31 +00:00
< p > In the same way that a < code > *i32< / code > can be {#link|implicitly cast|Implicit Casts#} to a
2018-05-31 14:56:59 +00:00
< code > *const i32< / code > , 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" {
2018-01-19 08:03:20 +00:00
assert(@typeOf(& foo).alignment == 4);
2018-05-31 14:56:59 +00:00
assert(@typeOf(& foo) == *align(4) u8);
2018-06-05 02:11:14 +00:00
const slice = (*[1]u8)(&foo)[0..];
2017-11-07 08:22:27 +00:00
assert(@typeOf(slice) == []align(4) u8);
}
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);
2018-01-25 09:10:11 +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#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
test "pointer alignment safety" {
2018-06-18 21:25:29 +00:00
var array align(4) = []u32{ 0x11111111, 0x11111111 };
const bytes = @sliceToBytes(array[0..]);
2017-11-07 08:22:27 +00:00
assert(foo(bytes) == 0x11111111);
}
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];
2018-06-18 21:25:29 +00:00
const int_slice = @bytesToSlice(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#}
{#header_open|Type Based Alias Analysis#}
2017-11-07 08:22:27 +00:00
< p > Zig uses Type Based Alias Analysis (also known as Strict Aliasing) to
perform some optimizations. This means that pointers of different types must
not alias the same memory, with the exception of < code > u8< / code > . Pointers to
< code > u8< / code > can alias any memory.
< / p >
< p > As an example, this code produces undefined behavior:< / p >
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @ptrCast(*u32, f32(12.34)).*< / code > < / pre >
2018-01-23 04:06:07 +00:00
< p > Instead, use {#link|@bitCast#}:
2017-11-07 08:22:27 +00:00
< pre > < code class = "zig" > @bitCast(u32, f32(12.34))< / code > < / pre >
2018-06-18 16:02:30 +00:00
< p > As an added benefit, the < code > @bitCast< / code > version works at compile-time.< / p >
2018-01-17 05:22:33 +00:00
{#see_also|Slices|Memory#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_close#}
{#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" {
2018-06-04 05:09:15 +00: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.
const slice = array[0..array.len];
2018-06-04 05:09:15 +00:00
assert(& slice[0] == &array[0]);
2017-11-07 08:22:27 +00:00
assert(slice.len == array.len);
2018-06-04 05:09:15 +00: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.
assert(@typeOf(slice.ptr) == [*]i32);
assert(@typeOf(& slice[0]) == *i32);
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 05:09:15 +00: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#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
const mem = @import("std").mem;
const fmt = @import("std").fmt;
test "using slices for strings" {
// Zig has no concept of strings. String literals are arrays of u8, and
// in general the string type is []u8 (slice of u8).
// Here we implicitly cast [5]u8 to []const u8
const hello: []const u8 = "hello";
const world: []const u8 = "世界";
var all_together: [100]u8 = undefined;
// You can use slice syntax on an array to convert an array into a slice.
const all_together_slice = all_together[0..];
2018-01-19 08:03:20 +00:00
// String concatenation example.
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 02:11:14 +00: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.
assert(@typeOf(slice) == []u8);
// You can also slice a slice:
const slice2 = slice[2..3];
assert(slice2.len == 1);
assert(slice2[0] == 3);
}
test "slice widening" {
// Zig supports slice widening and slice narrowing. Cast a slice of u8
// to a slice of anything else, and Zig will perform the length conversion.
2018-06-18 21:25:29 +00:00
const array align(@alignOf(u32)) = []u8{ 0x12, 0x12, 0x12, 0x12, 0x13, 0x13, 0x13, 0x13 };
const slice = @bytesToSlice(u32, array[0..]);
2017-11-07 08:22:27 +00:00
assert(slice.len == 2);
assert(slice[0] == 0x12121212);
assert(slice[1] == 0x13131313);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-01-17 05:22:33 +00:00
{#see_also|Pointers|for|Arrays#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|struct#}
2018-01-19 08:03:20 +00:00
{#code_begin|test|structs#}
// Declare a struct.
2017-11-07 08:22:27 +00:00
// Zig gives no guarantees about the order of fields and whether or
// not there will be padding.
const Point = struct {
x: f32,
y: f32,
};
// Maybe we want to pass it to OpenGL so we want to be particular about
// how the bytes are arranged.
const Point2 = packed struct {
x: f32,
y: f32,
};
// Declare an instance of a struct.
const p = Point {
.x = 0.12,
.y = 0.34,
};
// Maybe we're not ready to fill out some of the fields.
var p2 = Point {
.x = 0.12,
.y = undefined,
};
// Structs can have methods
// Struct methods are not special, they are only namespaced
// functions that you can call with dot syntax.
const Vec3 = struct {
x: f32,
y: f32,
z: f32,
2018-01-25 09:10:11 +00:00
pub fn init(x: f32, y: f32, z: f32) Vec3 {
2017-11-07 08:22:27 +00:00
return Vec3 {
.x = x,
.y = y,
.z = z,
};
}
2018-05-31 14:56:59 +00:00
pub fn dot(self: *const Vec3, other: *const 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.
const Empty = struct {
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
const does_nothing = Empty {};
}
// 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 14:56:59 +00: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" {
var point = Point {
.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 {
2017-11-07 08:22:27 +00:00
return struct {
pub const Node = struct {
2018-05-31 14:56:59 +00:00
prev: ?*Node,
next: ?*Node,
2017-11-07 08:22:27 +00:00
data: T,
};
2018-05-31 14:56:59 +00: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));
var list = LinkedList(i32) {
.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));
var node = ListOfInts.Node {
.prev = null,
.next = null,
.data = 1234,
};
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 03:42:14 +00:00
assert(list2.first.?.data == 1234);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
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.
const Type = enum {
Ok,
NotOk,
};
// Declare a specific instance of the enum variant.
2017-12-04 06:42:02 +00: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.
const Value = enum(u2) {
2017-11-07 08:22:27 +00:00
Zero,
One,
Two,
};
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" {
2018-06-19 07:50:38 +00: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.
const Value2 = enum(u32) {
Hundred = 100,
Thousand = 1000,
Million = 1000000,
};
test "set enum ordinal value" {
2018-06-19 07:50:38 +00: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.
const Suit = enum {
Clubs,
Spades,
Diamonds,
Hearts,
2018-01-25 09:10:11 +00:00
pub fn isClubs(self: Suit) bool {
2017-12-04 06:42:02 +00:00
return self == Suit.Clubs;
2017-11-07 08:22:27 +00:00
}
};
test "enum method" {
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.
const Foo = enum {
2017-12-04 06:42:02 +00:00
String,
Number,
None,
};
test "enum variant switch" {
const p = Foo.Number;
const what_is_it = switch (p) {
2018-01-19 08:03:20 +00: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.
const Small = enum {
One,
Two,
Three,
Four,
};
test "@TagType" {
assert(@TagType(Small) == u2);
}
// @memberCount tells how many fields an enum has:
test "@memberCount" {
assert(@memberCount(Small) == 4);
}
// @memberName tells the name of a field in an enum:
test "@memberName" {
assert(mem.eql(u8, @memberName(Small, 1), "Two"));
}
// @tagName gives a []const u8 representation of an enum value:
test "@tagName" {
assert(mem.eql(u8, @tagName(Small.Three), "Three"));
2018-01-19 08:03:20 +00:00
}
{#code_end#}
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 >
{#code_begin|obj_err|parameter of type 'Foo' not allowed in function with calling convention 'ccc'#}
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 >
For a C-ABI-compatible enum, use < code class = "zig" > extern enum< / code > :
< / p >
{#code_begin|obj#}
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#}
2018-04-06 23:14:49 +00:00
{#header_open|packed enum#}
< p > By default, the size of enums is not guaranteed.< / p >
< p > < code > packed enum< / code > causes the size of the enum to be the same as the size of the integer tag type
of the enum:< / p >
{#code_begin|test#}
const std = @import("std");
test "packed enum" {
const Number = packed enum(u8) {
One,
Two,
Three,
};
std.debug.assert(@sizeOf(Number) == @sizeOf(u8));
}
{#code_end#}
{#header_close#}
{#see_also|@memberName|@memberCount|@tagName|@sizeOf#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|union#}
2018-01-19 08:03:20 +00:00
{#code_begin|test|union#}
const assert = @import("std").debug.assert;
2017-12-04 06:42:02 +00:00
const mem = @import("std").mem;
// A union has only 1 active field at a time.
const Payload = union {
Int: i64,
Float: f64,
Bool: bool,
};
test "simple union" {
var payload = Payload {.Int = 1234};
// payload.Float = 12.34; // ERROR! field not active
assert(payload.Int == 1234);
// You can activate another field by assigning the entire union.
payload = Payload {.Float = 12.34};
assert(payload.Float == 12.34);
}
// Unions can be given an enum tag type:
const ComplexTypeTag = enum { Ok, NotOk };
const ComplexType = union(ComplexTypeTag) {
Ok: u8,
NotOk: void,
};
// Declare a specific instance of the union variant.
test "declare union value" {
const c = ComplexType { .Ok = 0 };
assert(ComplexTypeTag(c) == ComplexTypeTag.Ok);
}
// @TagType can be used to access the enum tag type of a union.
test "@TagType" {
assert(@TagType(ComplexType) == ComplexTypeTag);
}
// Unions can be made to infer the enum tag type.
const Foo = union(enum) {
2017-11-07 08:22:27 +00:00
String: []const u8,
Number: u64,
2017-12-04 06:42:02 +00:00
// void can be omitted when inferring enum tag type.
2017-11-07 08:22:27 +00:00
None,
};
2017-12-04 06:42:02 +00:00
test "union variant switch" {
const p = Foo { .Number = 54 };
2017-11-07 08:22:27 +00:00
const what_is_it = switch (p) {
// Capture by reference
2018-01-19 08:03:20 +00:00
Foo.String => |*x| blk: {
break :blk "this is a string";
2017-11-07 08:22:27 +00:00
},
// Capture by value
2018-01-19 08:03:20 +00:00
Foo.Number => |x| blk: {
2017-12-04 06:42:02 +00:00
assert(x == 54);
2018-01-19 08:03:20 +00:00
break :blk "this is a number";
2017-11-07 08:22:27 +00:00
},
2018-01-19 08:03:20 +00:00
Foo.None => blk: {
break :blk "this is a none";
},
2017-11-07 08:22:27 +00:00
};
2017-12-04 06:42:02 +00:00
assert(mem.eql(u8, what_is_it, "this is a number"));
2017-11-07 08:22:27 +00:00
}
2018-04-08 22:03:02 +00:00
// Unions can have methods just like structs and enums:
const Variant = union(enum) {
Int: i32,
Bool: bool,
2018-05-31 14:56:59 +00:00
fn truthy(self: *const Variant) bool {
2018-05-18 03:21:44 +00:00
return switch (self.*) {
2018-04-08 22:03:02 +00:00
Variant.Int => |x_int| x_int != 0,
Variant.Bool => |x_bool| x_bool,
};
}
};
test "union method" {
var v1 = Variant { .Int = 1 };
var v2 = Variant { .Bool = false };
assert(v1.truthy());
assert(!v2.truthy());
}
2017-12-04 06:42:02 +00:00
const Small = union {
A: i32,
B: bool,
C: u8,
2017-11-07 08:22:27 +00:00
};
2017-12-04 06:42:02 +00:00
// @memberCount tells how many fields a union has:
test "@memberCount" {
assert(@memberCount(Small) == 3);
}
// @memberName tells the name of a field in an enum:
test "@memberName" {
assert(mem.eql(u8, @memberName(Small, 1), "B"));
}
// @tagName gives a []const u8 representation of an enum value,
// but only if the union has an enum tag type.
const Small2 = union(enum) {
A: i32,
B: bool,
C: u8,
};
test "@tagName" {
assert(mem.eql(u8, @tagName(Small2.C), "C"));
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2017-12-04 06:42:02 +00:00
Unions with an enum tag are generated as a struct with a tag field and union field. Zig
2017-11-07 08:22:27 +00:00
sorts the order of the tag and union field by the largest alignment.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|switch#}
2018-01-19 08:03:20 +00:00
{#code_begin|test|switch#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
const builtin = @import("builtin");
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.
2018-01-19 08:03:20 +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);
}
test "switch enum" {
2018-01-19 08:03:20 +00:00
const Item = union(enum) {
2017-11-07 08:22:27 +00:00
A: u32,
C: struct { x: u8, y: u8 },
D,
};
2018-01-19 08:03:20 +00:00
var a = Item { .A = 3 };
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
// value matched.
2018-01-19 08:03:20 +00:00
Item.A => |item| item,
2017-11-07 08:22:27 +00:00
// A reference to the matched value can be obtained using `*` syntax.
2018-01-19 08:03:20 +00:00
Item.C => |*item| blk: {
2018-05-18 03:21:44 +00: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
2018-01-19 08:03:20 +00:00
Item.D => 8,
2017-11-07 08:22:27 +00:00
};
assert(b == 3);
}
// Switch expressions can be used outside a function:
const os_msg = switch (builtin.os) {
2018-01-19 08:03:20 +00:00
builtin.Os.linux => "we found a linux user",
else => "not a linux user",
2017-11-07 08:22:27 +00:00
};
// Inside a function, switch statements implicitly are compile-time
// evaluated if the target expression is compile-time known.
test "switch inside function" {
switch (builtin.os) {
2018-01-20 03:17:31 +00:00
builtin.Os.fuchsia => {
// On an OS other than fuchsia, block is not even analyzed,
2017-11-07 08:22:27 +00:00
// so this compile error is not triggered.
2018-01-20 03:17:31 +00:00
// On fuchsia this compile error would be triggered.
2018-07-14 15:52:48 +00:00
@compileError("fuchsia not supported");
2017-11-07 08:22:27 +00:00
},
2018-01-19 08:03:20 +00:00
else => {},
}
}
{#code_end#}
2018-01-17 05:22:33 +00:00
{#see_also|comptime|enum|@compileError|Compile Variables#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|while#}
2018-07-03 18:03:27 +00: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 18:03:27 +00:00
{#code_end#}
< p >
Use < code > break< / code > to exit a while loop early.
< / 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 18:03:27 +00:00
{#code_end#}
< p >
Use < code > continue< / code > to jump back to the beginning of the loop.
< / 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 18:03:27 +00:00
{#code_end#}
< p >
While loops support a continue expression which is executed when the loop
is continued. The < code > continue< / code > keyword respects this expression.
< / p >
{#code_begin|test|while#}
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
2018-07-14 15:52:48 +00: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 15:52:48 +00:00
test "while loop continue expression, more complicated" {
2018-07-16 14:53:15 +00: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 18:03:27 +00:00
{#code_end#}
< p >
While loops are expressions. The result of the expression is the
result of the < code > else< / code > clause of a while loop, which is executed when
the condition of the while loop is tested as false.
< / p >
< p >
< code > break< / code > , like < code > return< / code > , accepts a value
parameter. This is the result of the < code > while< / code > expression.
When you < code > break< / code > from a while loop, the < code > else< / code > branch is not
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 18:03:27 +00:00
{#code_end#}
{#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 >
When the < code > |x|< / code > syntax is present on a < code > while< / code > expression,
the while condition must have an {#link|Optional Type#}.
< / p >
< p >
The < code > else< / code > branch is allowed on optional iteration. In this case, it will
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 {
assert(sum1 == 3);
}
}
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 18:03:27 +00: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 >
When the < code > else |x|< / code > syntax is present on a < code > while< / code > expression,
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-02-08 08:02:41 +00:00
fn eventuallyErrorSequence() error!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 21:21:08 +00:00
{#code_end#}
2018-07-03 18:03:27 +00:00
{#header_close#}
2018-06-19 21:21:08 +00: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 21:21:08 +00:00
< p >
It is recommended to use < code > inline< / code > loops only for one of these reasons:
< / 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 03:42:14 +00: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" {
const items = []i32 { 4, 5, 3, 4, 0 };
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| {
assert(@typeOf(i) == usize);
2018-06-17 06:57:07 +00:00
sum2 += @intCast(i32, i);
2017-11-07 08:22:27 +00:00
}
assert(sum2 == 10);
}
test "for reference" {
var items = []i32 { 3, 4, 2 };
// Iterate over the slice by reference by
// specifying that the capture value is a pointer.
for (items) |*value| {
2018-05-18 03:21:44 +00: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.
var items = []?i32 { 3, 4, null, 5 };
// For loops can also be used as expressions.
var sum: i32 = 0;
const result = for (items) |value| {
if (value == null) {
break 9;
} else {
2018-06-10 03:42:14 +00:00
sum += value.?;
2017-11-07 08:22:27 +00:00
}
2018-01-19 08:03:20 +00:00
} else blk: {
2017-11-07 08:22:27 +00:00
assert(sum == 7);
2018-01-19 08:03:20 +00:00
break :blk sum;
2017-11-07 08:22:27 +00:00
};
}
2018-06-19 21:21:08 +00:00
{#code_end#}
{#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" {
const nums = []i32{2, 4, 6};
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 21:21:08 +00:00
< p >
It is recommended to use < code > inline< / code > loops only for one of these reasons:
< / 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-02-08 08:02:41 +00:00
// * error!T
2017-11-07 08:22:27 +00:00
const assert = @import("std").debug.assert;
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
}
// If expressions are used instead of a ternary expression.
const result = if (a != b) 47 else 3089;
assert(result == 47);
}
2018-06-10 03:42:14 +00: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 03:21:44 +00: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-02-08 08:02:41 +00:00
const a: error!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-02-08 08:02:41 +00:00
const b: error!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-02-08 08:02:41 +00:00
var c: error!u32 = 3;
2017-11-07 08:22:27 +00:00
if (c) |*value| {
2018-05-18 03:21:44 +00: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
}
{#code_end#}
2018-06-10 03:42:14 +00: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;
const warn = std.debug.warn;
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 {
2018-01-19 08:03:20 +00:00
warn("\n");
2017-11-07 08:22:27 +00:00
defer {
2018-01-19 08:03:20 +00:00
warn("1 ");
2017-11-07 08:22:27 +00:00
}
defer {
2018-01-19 08:03:20 +00:00
warn("2 ");
2017-11-07 08:22:27 +00:00
}
if (false) {
// defers are not run if they are never executed.
defer {
2018-01-19 08:03:20 +00:00
warn("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 {
2018-01-19 08:03:20 +00:00
warn("\nstart of function\n");
2017-11-07 08:22:27 +00:00
// This will always be executed on exit
defer {
2018-01-19 08:03:20 +00:00
warn("end of function\n");
2017-11-07 08:22:27 +00:00
}
2018-01-24 04:08:09 +00:00
errdefer {
2018-01-19 08:03:20 +00:00
warn("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" {
2017-11-07 08:22:27 +00:00
_ = deferErrorExample(false);
_ = deferErrorExample(true);
}
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 >
In < code > Debug< / code > and < code > ReleaseSafe< / code > mode, and when using < code > zig test< / code > ,
< code > unreachable< / code > emits a call to < code > panic< / code > with the message < code > reached unreachable code< / code > .
< / p >
< p >
In < code > ReleaseFast< / code > mode, the optimizer uses the assumption that < code > unreachable< / code > code
will never be hit to perform optimizations. However, < code > zig test< / code > even in < code > ReleaseFast< / code > mode
still emits < code > unreachable< / code > as calls to < code > panic< / code > .
< / 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
2018-01-19 08:03:20 +00:00
assert(@typeOf(unreachable) == noreturn);
}
}
{#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 >
< code > noreturn< / code > is the type of:
< / p >
< ul >
< li > < code > break< / code > < / li >
< li > < code > continue< / code > < / li >
< li > < code > return< / code > < / li >
< li > < code > unreachable< / code > < / li >
< li > < code > while (true) {}< / code > < / li >
< / ul >
< p > When resolving types together, such as < code > if< / code > clauses or < code > switch< / code > prongs,
the < code > noreturn< / code > type is compatible with every other type. Consider:
< / 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#}
2017-11-07 08:22:27 +00:00
< p > Another use case for < code > noreturn< / code > is the < code > exit< / code > function:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
{#target_windows#}
2018-01-25 09:10:11 +00:00
pub extern "kernel32" stdcallcc fn ExitProcess(exit_code: c_uint) 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-02-08 08:02:41 +00:00
fn bar() error!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) {
// You can still return manually if needed.
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.
// The stdcallcc specifier changes the calling convention of the function.
2018-01-25 09:10:11 +00:00
extern "kernel32" stdcallcc fn ExitProcess(exit_code: u32) noreturn;
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) {}
}
// nakedcc makes a function not have any function prologue or epilogue.
// This can be useful when integrating with assembly.
2018-01-25 09:10:11 +00:00
nakedcc fn _start() noreturn {
2017-11-07 08:22:27 +00:00
abort();
}
// 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 {
2018-01-25 09:10:11 +00:00
assert(@typeOf(foo) == fn()void);
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 >
2018-06-14 02:40:38 +00:00
In Zig, structs, unions, and enums with payloads can be passed directly to a function:
2017-11-07 08:22:27 +00:00
< / p >
2018-06-14 02:40:38 +00:00
{#code_begin|test#}
const Point = struct {
2017-11-07 08:22:27 +00:00
x: i32,
2018-06-14 02:40:38 +00:00
y: i32,
2017-11-07 08:22:27 +00:00
};
2018-06-14 02:40:38 +00:00
fn foo(point: Point) i32 {
return point.x + point.y;
2018-01-19 08:03:20 +00:00
}
2017-11-07 08:22:27 +00:00
2018-06-14 02:40:38 +00:00
const assert = @import("std").debug.assert;
2017-11-07 08:22:27 +00:00
2018-06-14 02:40:38 +00:00
test "pass aggregate type by non-copy value to function" {
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 02:40:38 +00:00
In this case, the value may be passed by reference, or by value, whichever way
Zig decides will be faster.
< / p >
< p >
For extern functions, Zig follows the C ABI for passing structs and unions by value.
2017-11-07 08:22:27 +00:00
< / p >
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" {
assert(@typeOf(assert).ReturnType == void);
assert(@typeOf(assert).is_var_args == false);
}
{#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-05-25 01:27:44 +00:00
However right now it is hard coded to be a < code > u16< / code > . See < a href = "https://github.com/ziglang/zig/issues/786" > #768< / a > .
2017-11-07 08:22:27 +00:00
< / p >
< p >
2018-07-06 20:20:31 +00:00
You can {#link|implicitly cast|Implicit Casts#} an error from a subset to its 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");
const FileOpenError = error {
AccessDenied,
OutOfMemory,
FileNotFound,
};
const AllocationError = error {
OutOfMemory,
};
test "implicit cast subset to superset" {
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 >
2018-02-24 01:43:47 +00:00
But you cannot implicitly cast an error from a superset to a subset:
< / p >
{#code_begin|test_err|not a member of destination error set#}
const FileOpenError = error {
AccessDenied,
OutOfMemory,
FileNotFound,
};
const AllocationError = error {
OutOfMemory,
};
test "implicit cast superset to subset" {
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#}
const err = (error {FileNotFound}).FileNotFound;
{#code_end#}
< p >
This becomes useful when using {#link|Inferred Error Sets#}.
< / p >
{#header_open|The Global Error Set#}
< p > < code > error< / code > refers to the global error set.
This is the error set that contains all errors in the entire compilation unit.
It is a superset of all other error sets and a subset of none of them.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2018-02-24 01:43:47 +00:00
You can implicitly cast any error set to the global one, and you can explicitly
cast an error of global error set to a non-global one. This inserts a language-level
assert to make sure the error value is in fact in the destination error set.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2018-03-25 22:48:07 +00: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-03-31 10:17:02 +00:00
An error set type and normal type can be combined with the < code > !< / code >
2018-03-25 22:48:07 +00: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-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,
else => @maxValue(u8),
};
}
test "parse u64" {
const result = try parseU64("1234", 10);
@import("std").debug.assert(result == 1234);
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-02-08 08:02:41 +00:00
Notice the return type is < code > !u64< / code > . This means that the function
either returns an unsigned 64 bit integer, or an error. We left off the error set
to the left of the < code > !< / code > , 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-02-08 08:02:41 +00:00
an error, and at the bottom a return statement that returns a < code > u64< / code > .
2018-07-06 20:20:31 +00:00
Both types {#link|implicitly cast|Implicit Casts#} to < code > error!u64< / code > .
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 22:12:05 +00:00
{#header_open|catch#}
2018-01-19 08:03:20 +00:00
< p > If you want to provide a default value, you can use the < code > catch< / code > binary operator:< / p >
{#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 >
In this code, < code > number< / code > will be equal to the successfully parsed string, or
2018-01-19 08:03:20 +00:00
a default value of 13. The type of the right hand side of the binary < code > catch< / code > operator must
2017-11-07 08:22:27 +00:00
match the unwrapped error union type, or be of type < code > noreturn< / code > .
< / p >
2018-06-14 22:12:05 +00: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-01-07 21:51:46 +00:00
There is a shortcut for this. The < code > try< / code > 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-01-07 21:51:46 +00:00
< code > try< / code > 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 22:12:05 +00: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
< code > unreachable< / code > value on the right hand side. < code > unreachable< / code > generates
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 22:12:05 +00: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 22:12:05 +00:00
{#header_open|errdefer#}
2017-11-07 08:22:27 +00:00
< p >
The other component to error handling is defer statements.
2018-06-14 22:12:05 +00:00
In addition to an unconditional {#link|defer#}, Zig has < code > errdefer< / code > ,
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 05:13:51 +00: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 22:12:05 +00: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-01-19 08:03:20 +00:00
to ignore the error, you can add < code > catch unreachable< / code > 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
errors not occuring. Just a small optimization benefit that is not available
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-02-09 01:45:26 +00:00
< p > An error union is created with the < code > !< / code > 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-02-09 01:45:26 +00:00
var foo: error!i32 = undefined;
2018-01-31 16:47:56 +00:00
// Implicitly cast from child type of an error union:
foo = 1234;
// Implicitly cast from an error set:
foo = error.SomeError;
2018-02-09 01:45:26 +00:00
// Use compile-time reflection to access the payload type of an error union:
comptime assert(@typeOf(foo).Payload == i32);
// Use compile-time reflection to access the error set type of an error union:
comptime assert(@typeOf(foo).ErrorSet == error);
2018-01-31 16:47:56 +00:00
}
{#code_end#}
2018-06-12 23:38:59 +00:00
{#header_open|Merging Error Sets#}
< p >
Use the < code > ||< / code > operator to merge two error sets together. The resulting
error set contains the errors of both error sets. Doc comments from the left-hand
side override doc comments from the right-hand side. In this example, the doc
comments for < code > C.PathNotFound< / code > is < code > A doc comment< / code > .
< / 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
< code > LinuxFileOpenError || WindowsFileOpenError< / code > for the error set of opening
files.
< / p >
{#code_begin|test#}
const A = error{
NotDir,
/// A doc comment
PathNotFound,
};
const B = error{
OutOfMemory,
/// B doc comment
PathNotFound,
};
const C = A || B;
fn foo() C!void {
return error.NotDir;
}
test "merge error sets" {
if (foo()) {
@panic("unexpected");
} else |err| switch (err) {
error.OutOfMemory => @panic("unexpected"),
error.PathNotFound => @panic("unexpected"),
error.NotDir => {},
}
}
{#code_end#}
{#header_close#}
2018-02-24 01:43:47 +00:00
{#header_open|Inferred Error Sets#}
2018-05-25 00:59:19 +00: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 00:43:59 +00:00
}
2018-05-25 00:59:19 +00: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 00:43:59 +00:00
}
2018-05-25 00:59:19 +00:00
const Error = error {
Overflow,
2018-05-17 00:43:59 +00:00
};
2018-05-25 00:59:19 +00: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 00:43:59 +00:00
{#code_end#}
2018-05-25 00:59:19 +00: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 22:12:05 +00: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 >
You can see that the final error bubbled up was < code > PermissionDenied< / code > ,
but the original error that started this whole thing was < code > FileNotFound< / code > . In the < code > bar< / code > function, the code handles the original error code,
and then returns another one, from the switch statement. Error Return Traces make this clear, whereas a stack trace would look like this:
< / 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
flow in < code > bar< / code > got to the < code > hello()< / code > call.
One would have to open a debugger or further instrument the application
in order to find out. The error return trace, on the other hand,
shows exactly how the error bubbled up.
< / 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 >
< li > An error makes its way to < code > catch unreachable< / code > and you have not overridden the default panic handler< / li >
< li > Use {#link|errorReturnTrace#} to access the current return trace. You can use < code > std.debug.dumpStackTrace< / code > to print it. This function returns comptime-known {#link|null#} when building without error return tracing support.< / li >
< / 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 >
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 < code > void< / code > calls a function returning < code > error< / code > .
This is to initialize this struct in the stack memory:
< / p >
{#code_begin|syntax#}
pub const StackTrace = struct {
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 >
A pointer to < code > StackTrace< / code > 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.
< / p >
< p >
That's it for the path when no errors occur. It's practically free in terms of performance.
< / p >
< p >
When generating the code for a function that returns an error, just before the < code > return< / code > statement (only for the < code > return< / code > statements that return errors), Zig generates a call to this function:
< / 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
< code > __zig_return_error< / code > 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.
< / 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 03:42:14 +00: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 03:42:14 +00:00
readability is with the optional type.
2017-11-07 08:22:27 +00:00
< / p >
< p >
2018-06-10 03:42:14 +00: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 03:42:14 +00: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-06-10 03:42:14 +00:00
Now the variable < code > optional_int< / code > could be an < code > i32< / code > , or < code > null< / code > .
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 03:42:14 +00: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 14:56:59 +00:00
extern fn malloc(size: size_t) ?*u8;
2017-11-07 08:22:27 +00:00
2018-05-31 14:56:59 +00:00
fn doAThing() ?*Foo {
2018-06-10 05:13:51 +00: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-06-10 05:13:51 +00:00
is < code > *u8< / code > < em > not< / em > < code > ?*u8< / code > . The < code > orelse< / code > keyword
2018-06-10 03:42:14 +00:00
unwrapped the optional type and therefore < code > ptr< / code > 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 03:42:14 +00:00
fn doAThing(optional_foo: ?*Foo) void {
2017-11-07 08:22:27 +00:00
// do some stuff
2018-06-10 03:42:14 +00: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-06-10 03:42:14 +00:00
< code > foo< / code > 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 03:42:14 +00:00
{#header_open|Optional Type#}
< p > An optional is created by putting < code > ?< / code > in front of a type. You can use compile-time
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 03:42:14 +00:00
test "optional type" {
// Declare an optional and implicitly cast from null:
2018-01-31 16:47:56 +00:00
var foo: ?i32 = null;
2018-06-10 03:42:14 +00:00
// Implicitly cast from child type of an optional
2018-01-31 16:47:56 +00:00
foo = 1234;
2018-06-10 03:42:14 +00:00
// Use compile-time reflection to access the child type of the optional:
2018-01-31 16:47:56 +00:00
comptime assert(@typeOf(foo).Child == i32);
}
2018-06-14 22:12:05 +00:00
{#code_end#}
{#header_close#}
{#header_open|null#}
< p >
Just like {#link|undefined#}, < code > null< / code > has its own type, and the only way to use it is to
cast it to a different type:
< / p >
{#code_begin|syntax#}
const optional_value: ?i32 = null;
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 18:43:55 +00:00
< p >
A < strong > type cast< / strong > converts a value of one type to another.
Zig has {#link|Implicit Casts#} for conversions that are known to be completely safe and unambiguous,
and {#link|Explicit Casts#} for conversions that one would not want to happen on accident.
There is also a third kind of type conversion called {#link|Peer Type Resolution#} for
the case when a result type must be decided given multiple operand types.
< / p >
{#header_open|Implicit Casts#}
< p >
An implicit cast occurs when one type is expected, but different type is provided:
< / p >
{#code_begin|test#}
test "implicit cast - variable declaration" {
var a: u8 = 1;
var b: u16 = a;
}
test "implicit cast - function call" {
var a: u8 = 1;
foo(a);
}
fn foo(b: u16) void {}
test "implicit cast - invoke a type as a function" {
var a: u8 = 1;
var b = u16(a);
}
{#code_end#}
2018-06-26 19:48:42 +00:00
< p >
Implicit casts are only allowed when it is completely unambiguous how to get from one type to another,
and the transformation is guaranteed to be safe.
< / p >
2018-06-21 18:43:55 +00:00
{#header_open|Implicit Cast: Stricter Qualification#}
< 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 >
< li > < code > const< / code > - non-const to const is allowed< / li >
< li > < code > volatile< / code > - non-volatile to volatile is allowed< / li >
< li > < code > align< / code > - bigger to smaller alignment is allowed < / li >
< 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#}
test "implicit cast - const qualification" {
var a: i32 = 1;
var b: *i32 = &a;
foo(b);
}
fn foo(a: *const i32) void {}
{#code_end#}
< p >
In addition, pointers implicitly cast to const optional pointers:
< / 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" {
const window_name = [1][*]const u8{c"window name"};
const x: [*]const ?[*]const u8 = &window_name;
assert(mem.eql(u8, std.cstr.toSliceConst(x[0].?), "window name"));
}
{#code_end#}
{#header_close#}
{#header_open|Implicit Cast: Integer and Float Widening#}
< p >
{#link|Integers#} implicitly cast to integer types which can represent every value of the old type, and likewise
{#link|Floats#} implicitly cast to float types which can represent every value of the old type.
< / 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" {
2018-06-27 16:59:12 +00:00
var a: f16 = 12.34;
var b: f32 = a;
var c: f64 = b;
var d: f128 = c;
assert(d == a);
2018-06-21 18:43:55 +00:00
}
{#code_end#}
{#header_close#}
{#header_open|Implicit Cast: Arrays#}
< p > TODO: [N]T to []const T< / p >
< p > TODO: *const [N]T to []const T< / p >
< p > TODO: [N]T to *const []const T< / p >
< p > TODO: [N]T to ?[]const T< / p >
< p > TODO: *[N]T to []T< / p >
< p > TODO: *[N]T to [*]T< / p >
< p > TODO: *T to *[1]T< / p >
< p > TODO: [N]T to E![]const T< / p >
{#header_close#}
{#header_open|Implicit Cast: Optionals#}
< p > TODO: T to ?T< / p >
< p > TODO: T to E!?T< / p >
< p > TODO: null to ?T< / p >
{#header_close#}
{#header_open|Implicit Cast: T to E!T#}
< p > TODO< / p >
{#header_close#}
{#header_open|Implicit Cast: E to E!T#}
< p > TODO< / p >
{#header_close#}
{#header_open|Implicit Cast: comptime_int to *const integer#}
< p > TODO< / p >
{#header_close#}
{#header_open|Implicit Cast: comptime_float to *const float#}
< p > TODO< / p >
{#header_close#}
{#header_open|Implicit Cast: compile-time known numbers#}
< p > TODO< / p >
{#header_close#}
{#header_open|Implicit Cast: union to enum#}
< p > TODO< / p >
{#header_close#}
{#header_open|Implicit Cast: enum to union#}
< p > TODO< / p >
{#header_close#}
{#header_open|Implicit Cast: T to *T when @sizeOf(T) == 0#}
< p > TODO< / p >
{#header_close#}
{#header_open|Implicit Cast: undefined#}
< p > TODO< / p >
{#header_close#}
{#header_open|Implicit Cast: T to *const T#}
< p > TODO< / p >
{#header_close#}
{#header_close#}
{#header_open|Explicit Casts#}
2018-06-26 19:48:42 +00: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|@bytesToSlice#} - convert a slice of bytes to a slice of another type< / 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|@sliceToBytes#} - convert a slice of anything to a slice of bytes< / li >
< li > {#link|@truncate#} - convert between integer types, chopping off bits< / li >
< / ul >
2018-06-21 18:43:55 +00:00
{#header_close#}
{#header_open|Peer Type Resolution#}
< p > TODO< / p >
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 16:02:30 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|void#}
2018-06-18 16:02:30 +00:00
< p >
< code > void< / code > represents a type that has no value. Code that makes use of void values is
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#}
< p > When this turns into LLVM IR, there is no code generated in the body of < code > entry< / code > ,
even in debug mode. For example, on x86_64:< / p >
< 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 >
< p >
< code > void< / code > can be useful for instantiating generic types. For example, given a
< code > Map(Key, Value)< / code > , one can pass < code > void< / code > for the < code > Value< / code >
type to make it into a < code > Set< / code > :
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
test "turn HashMap into a set with void" {
var map = std.HashMap(i32, void, hash_i32, eql_i32).init(std.debug.global_allocator);
defer map.deinit();
_ = try map.put(1, {});
_ = try map.put(2, {});
assert(map.contains(2));
assert(!map.contains(3));
_ = map.remove(2);
assert(!map.contains(2));
}
fn hash_i32(x: i32) u32 {
return @bitCast(u32, x);
}
fn eql_i32(a: i32, b: i32) bool {
return a == b;
}
{#code_end#}
< p > Note that this is different than using a dummy value for the hash map value.
By using < code > void< / code > as the type of the value, the hash map entry type has no value field, and
thus the hash map takes up less space. Further, all the code that deals with storing and loading the
value is deleted, as seen above.
< / p >
< p >
< code > void< / code > is distinct from < code > c_void< / code > , which is defined like this:
< code > pub const c_void = @OpaqueType();< / code > .
< code > void< / code > has a known size of 0 bytes, and < code > c_void< / code > has an unknown, but non-zero, size.
< / p >
< p >
Expressions of type < code > void< / code > are the only ones whose value can be ignored. For example:
< / p >
{#code_begin|test_err|expression value is ignored#}
test "ignoring expression value" {
foo();
}
fn foo() i32 {
return 1234;
}
{#code_end#}
< p > However, if the expression has type < code > void< / code > :< / p >
{#code_begin|test#}
test "ignoring expression value" {
foo();
}
fn foo() void {}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 16:02:30 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|this#}
2017-11-07 08:22:27 +00:00
< p > TODO: example of this referring to Self struct< / p >
< p > TODO: example of this referring to recursion function< / p >
2018-01-25 06:46:12 +00:00
< p > TODO: example of this referring to basic block for @setRuntimeSafety< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#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 > ,
which is why the parameter < code > T< / code > in the above snippet must be marked with < code > comptime< / code > .
< / p >
< p >
A < code > comptime< / code > parameter means that:
< / 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 >
< / p >
< p >
For example, if we were to introduce another function to the above snippet:
< / 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
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 >
On the flip side, inside the function definition with the < code > comptime< / code > parameter, the
value is known at compile-time. This means that we actually could make this work for the bool type
if we wanted to:
< / 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 >
This works because Zig implicitly inlines < code > if< / code > expressions when the condition
is known at compile-time, and the compiler guarantees that it will skip analysis of
the branch not taken.
< / p >
< p >
This means that the actual function generated for < code > max< / code > in this situation looks like
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 >
This works the same way for < code > switch< / code > expressions - they are implicitly inlined
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 >
In Zig, the programmer can label variables as < code > comptime< / code > . This guarantees to the compiler
that every load and store of the variable is performed at compile-time. Any violation of this results in a
compile error.
< / p >
< p >
This combined with the fact that we can < code > inline< / code > loops allows us to write
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
const CmdFn = struct {
name: []const u8,
2018-01-25 09:10:11 +00:00
func: fn(i32) i32,
2017-11-07 08:22:27 +00:00
};
const cmd_fns = []CmdFn{
CmdFn {.name = "one", .func = one},
CmdFn {.name = "two", .func = two},
CmdFn {.name = "three", .func = three},
};
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
different code. In this example, the function < code > performFn< / code > is generated three different times,
for the different values of < code > prefix_char< / code > provided:
< / 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
use a < code > comptime< / code > expression to guarantee that the expression will be evaluated at compile-time.
If this cannot be accomplished, the compiler will emit an error. For example:
< / 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 >
It doesn't make sense that a program could call < code > exit()< / code > (or any other external function)
at compile-time, so this is a compile error. However, a < code > comptime< / code > expression does much
more than sometimes cause a compile error.
< / p >
< p >
Within a < code > comptime< / code > expression:
< / p >
< ul >
< li > All variables are < code > comptime< / code > variables.< / li >
2018-01-24 04:12:38 +00:00
< li > All < code > if< / code > , < code > while< / code > , < code > for< / code > , and < code > switch< / code >
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 >
What if we fix the base case, but put the wrong value in the < code > assert< / code > line?
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|encountered @panic at compile-time#}
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 >
What happened is Zig started interpreting the < code > assert< / code > function with the
parameter < code > ok< / code > set to < code > false< / code > . When the interpreter hit
< code > unreachable< / code > it emitted a compile error, because reaching unreachable
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
< code > comptime< / code > expressions. This means that we can use functions to
initialize complex static data. For example:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
const first_25_primes = firstNPrimes(25);
2017-11-07 08:22:27 +00:00
const sum_of_first_25_primes = sum(first_25_primes);
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,
we could call the < code > sum< / code > function as is with a slice of numbers whose length and values were
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 >
Here is an example of a generic < code > List< / code > data structure, that we will instantiate with
the type < code > i32< / code > . In Zig we refer to the type as < code > List(i32)< / code > .
< / 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-01-19 08:03:20 +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 >
That's it. It's a function that returns an anonymous < code > struct< / code > . For the purposes of error messages
and debugging, Zig infers the name < code > "List(i32)"< / code > from the function name and parameters invoked when creating
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#}
const Node = struct {
2018-05-31 14:56:59 +00: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,
< code > Node< / code > refers to itself as a pointer, which is not actually an infinite regression, so
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-01-17 08:24:03 +00:00
Putting all of this together, let's see how < code > printf< / code > works in Zig.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 08:24:03 +00:00
{#code_begin|exe|printf#}
const warn = @import("std").debug.warn;
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 {
2017-11-07 08:22:27 +00:00
warn("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.
2018-05-31 14:56:59 +00:00
pub fn printf(self: *OutStream, comptime format: []const u8, args: ...) error!void {
2017-11-07 08:22:27 +00:00
const State = enum {
Start,
OpenBrace,
CloseBrace,
};
comptime var start_index: usize = 0;
comptime var state = State.Start;
comptime var next_arg: usize = 0;
inline for (format) |c, i| {
switch (state) {
2018-01-19 08:03:20 +00:00
State.Start => switch (c) {
'{' => {
if (start_index < i ) try self . write ( format [ start_index . . i ] ) ;
2017-11-07 08:22:27 +00:00
state = State.OpenBrace;
},
2018-01-19 08:03:20 +00:00
'}' => {
if (start_index < i ) try self . write ( format [ start_index . . i ] ) ;
2017-11-07 08:22:27 +00:00
state = State.CloseBrace;
},
2018-01-19 08:03:20 +00:00
else => {},
2017-11-07 08:22:27 +00:00
},
2018-01-19 08:03:20 +00:00
State.OpenBrace => switch (c) {
'{' => {
2017-11-07 08:22:27 +00:00
state = State.Start;
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;
state = State.Start;
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
},
2018-01-19 08:03:20 +00:00
State.CloseBrace => switch (c) {
'}' => {
2017-11-07 08:22:27 +00:00
state = State.Start;
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 14:56:59 +00: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 >
< code > printValue< / code > is a function that takes a parameter of any type, and does different things depending
on the type:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
2018-05-31 14:56:59 +00:00
pub fn printValue(self: *OutStream, value: var) !void {
2017-11-07 08:22:27 +00:00
const T = @typeOf(value);
if (@isInteger(T)) {
return self.printInt(T, value);
} else if (@isFloat(T)) {
return self.printFloat(T, value);
} else {
@compileError("Unable to print type '" ++ @typeName(T) ++ "'");
}
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
And now, what happens if we give too many arguments to < code > printf< / code > ?
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|Unused arguments#}
const warn = @import("std").debug.warn;
const a_number: i32 = 1234;
const a_string = "foobar";
test "printf too many arguments" {
warn("here is a string: '{}' here is a number: {}\n",
a_string, a_number, a_number);
}
{#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,
only that it is a compile-time known value that is implicitly castable to a < code > []const u8< / code > :
< / p >
2018-01-17 08:24:03 +00:00
{#code_begin|exe|printf#}
const warn = @import("std").debug.warn;
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 {
2017-11-07 08:22:27 +00:00
warn(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 21:21:08 +00:00
{#see_also|inline while|inline for#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Assembly#}
2017-11-07 08:22:27 +00:00
< p > TODO: example of inline assembly< / p >
< p > TODO: example of module level assembly< / p >
< p > TODO: example of using inline assembly return value< / p >
< p > TODO: example of using inline assembly assigning values to variables< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#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 21:34:45 +00:00
{#header_close#}
{#header_open|Coroutines#}
< p >
A coroutine is a generalization of a function.
< / p >
< p >
When you call a function, it creates a stack frame,
and then the function runs until it reaches a return
statement, and then the stack frame is destroyed.
At the callsite, the next line of code does not run
until the function returns.
< / p >
< p >
A coroutine is like a function, but it can be suspended
and resumed any number of times, and then it must be
explicitly destroyed. When a coroutine suspends, it
returns to the resumer.
< / p >
{#header_open|Minimal Coroutine Example#}
< p >
Declare a coroutine with the < code > async< / code > keyword.
The expression in angle brackets must evaluate to a struct
which has these fields:
< / p >
< ul >
< li > < code > allocFn: fn (self: *Allocator, byte_count: usize, alignment: u29) Error![]u8< / code > - where < code > Error< / code > can be any error set.< / li >
< li > < code > freeFn: fn (self: *Allocator, old_mem: []u8) void< / code > < / li >
< / ul >
< p >
You may notice that this corresponds to the < code > std.mem.Allocator< / code > interface.
This makes it convenient to integrate with existing allocators. Note, however,
that the language feature does not depend on the standard library, and any struct which
has these fields is allowed.
< / p >
< p >
Omitting the angle bracket expression when defining an async function makes
the function generic. Zig will infer the allocator type when the async function is called.
< / p >
< p >
Call a coroutine with the < code > async< / code > keyword. Here, the expression in angle brackets
is a pointer to the allocator struct that the coroutine expects.
< / p >
< p >
The result of an async function call is a < code > promise->T< / code > type, where < code > T< / code >
is the return type of the async function. Once a promise has been created, it must be
consumed, either with < code > cancel< / code > or < code > await< / code > :
< / p >
< p >
Async functions start executing when created, so in the following example, the entire
async function completes before it is canceled:
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
var x: i32 = 1;
test "create a coroutine and cancel it" {
const p = try async< std.debug.global_allocator > simpleAsyncFn();
comptime assert(@typeOf(p) == promise->void);
cancel p;
assert(x == 2);
}
async< *std.mem.Allocator> fn simpleAsyncFn() void {
x += 1;
}
{#code_end#}
{#header_close#}
{#header_open|Suspend and Resume#}
< p >
At any point, an async function may suspend itself. This causes control flow to
return to the caller or resumer. The following code demonstrates where control flow
goes:
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
test "coroutine suspend, resume, cancel" {
seq('a');
const p = try async< std.debug.global_allocator > testAsyncSeq();
seq('c');
resume p;
seq('f');
cancel p;
seq('g');
assert(std.mem.eql(u8, points, "abcdefg"));
}
async fn testAsyncSeq() void {
defer seq('e');
seq('b');
suspend;
seq('d');
}
var points = []u8{0} ** "abcdefg".len;
var index: usize = 0;
fn seq(c: u8) void {
points[index] = c;
index += 1;
}
{#code_end#}
< p >
When an async function suspends itself, it must be sure that it will be
resumed or canceled somehow, for example by registering its promise handle
in an event loop. Use a suspend capture block to gain access to the
promise:
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
test "coroutine suspend with block" {
const p = try async< std.debug.global_allocator > testSuspendBlock();
std.debug.assert(!result);
resume a_promise;
std.debug.assert(result);
cancel p;
}
var a_promise: promise = undefined;
var result = false;
async fn testSuspendBlock() void {
2018-07-29 08:19:36 +00:00
suspend {
comptime assert(@typeOf(@handle()) == promise->void);
a_promise = @handle();
2018-06-11 21:34:45 +00:00
}
result = true;
}
{#code_end#}
< p >
Every suspend point in an async function represents a point at which the coroutine
could be destroyed. If that happens, < code > defer< / code > expressions that are in
scope are run, as well as < code > errdefer< / code > expressions.
< / p >
< p >
{#link|Await#} counts as a suspend point.
< / p >
{#header_open|Breaking from Suspend Blocks#}
< p >
Suspend blocks support labeled break, just like {#link|while#} and {#link|for#}.
< / p >
< p >
Upon entering a < code > suspend< / code > block, the coroutine is already considered
suspended, and can be resumed. For example, if you started another kernel thread,
and had that thread call < code > resume< / code > on the promise handle provided by the
< code > suspend< / code > block, the new thread would begin executing after the suspend
block, while the old thread continued executing the suspend block.
< / p >
< p >
2018-07-30 17:07:04 +00:00
However, the coroutine can be directly resumed from the suspend block, in which case it
2018-06-11 21:34:45 +00: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 17:07:04 +00:00
test "resume from suspend" {
2018-06-11 21:34:45 +00:00
var buf: [500]u8 = undefined;
var a = &std.heap.FixedBufferAllocator.init(buf[0..]).allocator;
var my_result: i32 = 1;
2018-07-30 17:07:04 +00:00
const p = try async< a > testResumeFromSuspend(&my_result);
2018-06-11 21:34:45 +00:00
cancel p;
std.debug.assert(my_result == 2);
}
2018-07-30 17:07:04 +00:00
async fn testResumeFromSuspend(my_result: *i32) void {
2018-08-02 08:45:35 +00:00
suspend {
resume @handle();
2018-06-11 21:34:45 +00:00
}
my_result.* += 1;
suspend;
my_result.* += 1;
}
{#code_end#}
{#header_close#}
{#header_close#}
{#header_open|Await#}
< p >
The < code > await< / code > keyword is used to coordinate with an async function's
< code > return< / code > statement.
< / p >
< p >
< code > await< / code > is valid only in an < code > async< / code > function, and it takes
as an operand a promise handle.
If the async function associated with the promise handle has already returned,
then < code > await< / code > destroys the target async function, and gives the return value.
Otherwise, < code > await< / code > suspends the current async function, registering its
promise handle with the target coroutine. It becomes the target coroutine's responsibility
to have ensured that it will be resumed or destroyed. When the target coroutine reaches
its return statement, it gives the return value to the awaiter, destroys itself, and then
resumes the awaiter.
< / p >
< p >
A promise handle must be consumed exactly once after it is created, either by < code > cancel< / code > or < code > await< / code > .
< / p >
< p >
< code > await< / code > counts as a suspend point, and therefore at every < code > await< / code > ,
a coroutine can be potentially destroyed, which would run < code > defer< / code > and < code > errdefer< / code > expressions.
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
var a_promise: promise = undefined;
var final_result: i32 = 0;
test "coroutine await" {
seq('a');
const p = async< std.debug.global_allocator > amain() catch unreachable;
seq('f');
resume a_promise;
seq('i');
assert(final_result == 1234);
assert(std.mem.eql(u8, seq_points, "abcdefghi"));
}
async fn amain() void {
seq('b');
const p = async another() catch unreachable;
seq('e');
final_result = await p;
seq('h');
}
async fn another() i32 {
seq('c');
2018-07-29 08:19:36 +00:00
suspend {
2018-06-11 21:34:45 +00:00
seq('d');
2018-07-29 08:19:36 +00:00
a_promise = @handle();
2018-06-11 21:34:45 +00:00
}
seq('g');
return 1234;
}
var seq_points = []u8{0} ** "abcdefghi".len;
var seq_index: usize = 0;
fn seq(c: u8) void {
seq_points[seq_index] = c;
seq_index += 1;
}
{#code_end#}
< p >
In general, < code > suspend< / code > is lower level than < code > await< / code > . Most application
code will use only < code > async< / code > and < code > await< / code > , but event loop
implementations will make use of < code > suspend< / code > internally.
< / p >
{#header_close#}
{#header_open|Open Issues#}
< p >
There are a few issues with coroutines that are considered unresolved. Best be aware of them,
as the situation is likely to change before 1.0.0:
< / p >
< ul >
< li > Async functions have optimizations disabled - even in release modes - due to an
< a href = "https://github.com/ziglang/zig/issues/802" > LLVM bug< / a > .
< / li >
< li >
There are some situations where we can know statically that there will not be
memory allocation failure, but Zig still forces us to handle it.
TODO file an issue for this and link it here.
< / li >
< li >
Zig does not take advantage of LLVM's allocation elision optimization for
coroutines. It crashed LLVM when I tried to do it the first time. This is
related to the other 2 bullet points here. See
< a href = "https://github.com/ziglang/zig/issues/802" > #802< / a > .
< / li >
< / ul >
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Builtin Functions#}
2017-11-07 08:22:27 +00:00
< p >
Builtin functions are provided by the compiler and are prefixed with < code > @< / code > .
The < code > comptime< / code > keyword on a parameter means that the parameter must be known
at compile time.
< / p >
2018-01-17 04:19:05 +00:00
{#header_open|@addWithOverflow#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @addWithOverflow(comptime T: type, a: T, b: T, result: *T) bool< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-05-18 03:21:44 +00:00
Performs < code > result.* = a + b< / code > . If overflow or underflow occurs,
2017-11-07 08:22:27 +00:00
stores the overflowed bits in < code > result< / code > and returns < code > true< / code > .
If no overflow or underflow occurs, returns < code > false< / code > .
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@ArgType#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @ArgType(comptime T: type, comptime n: usize) type< / code > < / pre >
2018-05-17 00:43:59 +00:00
< p >
2018-05-25 00:59:19 +00:00
This builtin function takes a function type and returns the type of the parameter at index < code > n< / code > .
2018-05-17 00:43:59 +00:00
< / p >
< p >
2018-05-25 00:59:19 +00:00
< code > T< / code > must be a function type.
< / p >
< p >
Note: This function is deprecated. Use {#link|@typeInfo#} instead.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-04-15 22:12:00 +00:00
{#header_open|@atomicLoad#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @atomicLoad(comptime T: type, ptr: *const T, comptime ordering: builtin.AtomicOrder) T< / code > < / pre >
2018-04-15 22:12:00 +00:00
< p >
This builtin function atomically dereferences a pointer and returns the value.
< / p >
< p >
< code > T< / code > must be a pointer type, a < code > bool< / code > ,
or an integer whose bit count meets these requirements:
< / p >
< ul >
< li > At least 8< / li >
< li > At most the same as usize< / li >
< li > Power of 2< / li >
< / ul >
< p >
TODO right now bool is not accepted. Also I think we could make non powers of 2 work fine, maybe
we can remove this restriction
< / p >
{#header_close#}
2018-03-01 02:19:51 +00:00
{#header_open|@atomicRmw#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @atomicRmw(comptime T: type, ptr: *T, comptime op: builtin.AtomicRmwOp, operand: T, comptime ordering: builtin.AtomicOrder) T< / code > < / pre >
2018-03-01 02:19:51 +00:00
< p >
This builtin function atomically modifies memory and then returns the previous value.
< / p >
< p >
< code > T< / code > must be a pointer type, a < code > bool< / code > ,
or an integer whose bit count meets these requirements:
< / p >
< ul >
< li > At least 8< / li >
< li > At most the same as usize< / li >
< li > Power of 2< / li >
< / ul >
< p >
TODO right now bool is not accepted. Also I think we could make non powers of 2 work fine, maybe
we can remove this restriction
< / p >
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@bitCast#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @bitCast(comptime DestType: type, value: var) DestType< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
Converts a value of one type to another type.
< / p >
< p >
Asserts that < code > @sizeOf(@typeOf(value)) == @sizeOf(DestType)< / code > .
< / p >
< p >
Asserts that < code > @typeId(DestType) != @import("builtin").TypeId.Pointer< / code > . Use < code > @ptrCast< / code > or < code > @intToPtr< / code > if you need this.
< / p >
< p >
Can be used for these things for example:
< / p >
< ul >
< li > Convert < code > f32< / code > to < code > u32< / code > bits< / li >
< li > Convert < code > i32< / code > to < code > u32< / code > preserving twos complement< / li >
< / ul >
< p >
Works at compile-time if < code > value< / code > 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.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@breakpoint#}
2017-11-07 08:22:27 +00:00
< pre > < code class = "zig" > @breakpoint()< / code > < / 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 >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@alignCast#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @alignCast(comptime alignment: u29, ptr: var) var< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-05-31 14:56:59 +00:00
< code > ptr< / code > can be < code > *T< / code > , < code > fn()< / code > , < code > ?*T< / code > ,
2017-11-07 08:22:27 +00:00
< code > ?fn()< / code > , or < code > []T< / code > . It returns the same type as < code > ptr< / code >
except with the alignment adjusted to the new value.
< / p >
2018-01-23 04:06:07 +00:00
< p > A {#link|pointer alignment safety check|Incorrect Pointer Alignment#} is added
2017-11-07 08:22:27 +00:00
to the generated code to make sure the pointer is aligned as promised.< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@alignOf#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @alignOf(comptime T: type) (number literal)< / code > < / pre >
2017-11-07 08:22:27 +00:00
< 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 > < code class = "zig" > const assert = @import("std").debug.assert;
comptime {
2018-05-31 14:56:59 +00:00
assert(*u32 == *align(@alignOf(u32)) u32);
2017-11-07 08:22:27 +00:00
}< / code > < / pre >
< p >
The result is a target-specific compile time constant. It is guaranteed to be
2018-01-23 04:06:07 +00:00
less than or equal to {#link|@sizeOf(T)|@sizeOf#}.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 05:22:33 +00:00
{#see_also|Alignment#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 07:07:16 +00:00
{#header_open|@boolToInt#}
< pre > < code class = "zig" > @boolToInt(value: bool) u1< / code > < / pre >
< p >
Converts < code > true< / code > to < code > u1(1)< / code > and < code > false< / code > to
< code > u1(0)< / code > .
< / p >
< p >
If the value is known at compile-time, the return type is < code > comptime_int< / code >
instead of < code > u1< / code > .
< / p >
{#header_close#}
2018-06-18 21:25:29 +00:00
{#header_open|@bytesToSlice#}
< pre > < code class = "zig" > @bytesToSlice(comptime Element: type, bytes: []u8) []Element< / code > < / pre >
< p >
Converts a slice of bytes or array of bytes into a slice of < code > Element< / code > .
The resulting slice has the same {#link|pointer|Pointers#} properties as the parameter.
< / p >
< p >
Attempting to convert a number of bytes with a length that does not evenly divide into a slice of
2018-06-18 22:48:29 +00:00
elements results in safety-protected {#link|Undefined Behavior#}.
2018-06-18 21:25:29 +00:00
< / p >
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@cDefine#}
2017-11-07 08:22:27 +00:00
< pre > < code class = "zig" > @cDefine(comptime name: []u8, value)< / code > < / pre >
< p >
This function can only occur inside < code > @cImport< / code > .
< / p >
< p >
This appends < code > #define $name $value< / code > to the < code > @cImport< / code >
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 >
< pre > < code class = "zig" > @cDefine("_GNU_SOURCE", {})< / code > < / 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#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @cImport(expression) (namespace)< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
This function parses C code and imports the functions, types, variables, and
compatible macro definitions into the result namespace.
< / p >
< p >
< code > expression< / code > is interpreted at compile time. The builtin functions
< code > @cInclude< / code > , < code > @cDefine< / code > , and < code > @cUndef< / code > work
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 >
Usually you should only have one < code > @cImport< / code > in your entire application, because it saves the compiler
from invoking clang multiple times, and prevents inline functions from being duplicated.
< / p >
< p >
Reasons for having multiple < code > @cImport< / code > expressions would be:
< / p >
< ul >
< li > To avoid a symbol collision, for example if foo.h and bar.h both < code > #define CONNECTION_COUNT< / code > < / li >
< 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#}
2017-11-07 08:22:27 +00:00
< pre > < code class = "zig" > @cInclude(comptime path: []u8)< / code > < / pre >
< p >
This function can only occur inside < code > @cImport< / code > .
< / p >
< p >
This appends < code > #include < $path>\n< / code > to the < code > c_import< / code >
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#}
{#header_open|@cUndef#}
2017-11-07 08:22:27 +00:00
< pre > < code class = "zig" > @cUndef(comptime name: []u8)< / code > < / pre >
< p >
This function can only occur inside < code > @cImport< / code > .
< / p >
< p >
This appends < code > #undef $name< / code > to the < code > @cImport< / code >
temporary buffer.
< / p >
2018-01-17 05:22:33 +00:00
{#see_also|Import from C Header File|@cImport|@cDefine|@cInclude#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@clz#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @clz(x: T) U< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
This function counts the number of leading zeroes in < code > x< / code > which is an integer
type < code > T< / code > .
< / p >
< p >
The return type < code > U< / code > is an unsigned integer with the minimum number
of bits that can represent the value < code > T.bit_count< / code > .
< / p >
< p >
If < code > x< / code > is zero, < code > @clz< / code > returns < code > T.bit_count< / code > .
< / p >
2018-07-07 04:25:32 +00:00
{#see_also|@ctz|@popCount#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-04-18 16:16:42 +00:00
{#header_open|@cmpxchgStrong#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @cmpxchgStrong(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-04-18 16:16:42 +00: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 14:56:59 +00:00
fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T {
2018-05-18 03:21:44 +00:00
const old_value = ptr.*;
2018-04-18 16:16:42 +00:00
if (old_value == expected_value) {
2018-05-18 03:21:44 +00:00
ptr.* = new_value;
2018-04-18 16:16:42 +00: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 >
< code > AtomicOrder< / code > can be found with < code > @import("builtin").AtomicOrder< / code > .
< / p >
< p > < code > @typeOf(ptr).alignment< / code > must be < code > > = @sizeOf(T).< / code > < / p >
2018-04-18 16:16:42 +00:00
{#see_also|Compile Variables|cmpxchgWeak#}
{#header_close#}
{#header_open|@cmpxchgWeak#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @cmpxchgWeak(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T< / code > < / pre >
2018-04-18 16:16:42 +00: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 14:56:59 +00:00
fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T {
2018-05-18 03:21:44 +00:00
const old_value = ptr.*;
2018-04-18 16:16:42 +00:00
if (old_value == expected_value and usuallyTrueButSometimesFalse()) {
2018-05-18 03:21:44 +00:00
ptr.* = new_value;
2018-04-18 16:16:42 +00:00
return null;
} else {
return old_value;
}
}
{#code_end#}
< p >
If you are using cmpxchg in a loop, the sporadic failure will be no problem, and < code > cmpxchgWeak< / code >
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 >
< code > AtomicOrder< / code > can be found with < code > @import("builtin").AtomicOrder< / code > .
< / p >
< p > < code > @typeOf(ptr).alignment< / code > must be < code > > = @sizeOf(T).< / code > < / p >
{#see_also|Compile Variables|cmpxchgStrong#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@compileError#}
2017-11-07 08:22:27 +00:00
< pre > < code class = "zig" > @compileError(comptime msg: []u8)< / code > < / pre >
< p >
This function, when semantically analyzed, causes a compile error with the
message < code > msg< / code > .
< / p >
< p >
There are several ways that code avoids being semantically checked, such as
using < code > if< / code > or < code > switch< / code > with compile time constants,
and < code > comptime< / code > functions.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@compileLog#}
2017-11-07 08:22:27 +00:00
< pre > < code class = "zig" > @compileLog(args: ...)< / code > < / pre >
< 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#}
const warn = @import("std").debug.warn;
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;
@compileLog("comptime val1 = ", val1);
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" {
2017-11-07 08:22:27 +00:00
@compileLog("comptime in main");
warn("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 >
< p >
will ouput:
< / p >
< p >
If all < code > @compileLog< / code > calls are removed or
not encountered by analysis, the
program compiles successfully and the generated executable prints:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|test#}
const warn = @import("std").debug.warn;
const num1 = blk: {
var val1: i32 = 99;
val1 = val1 + 1;
break :blk val1;
};
test "main" {
warn("Runtime in main, num1 = {}.\n", num1);
}
{#code_end#}
{#header_close#}
{#header_open|@ctz#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @ctz(x: T) U< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
This function counts the number of trailing zeroes in < code > x< / code > which is an integer
type < code > T< / code > .
< / p >
< p >
The return type < code > U< / code > is an unsigned integer with the minimum number
of bits that can represent the value < code > T.bit_count< / code > .
< / p >
< p >
If < code > x< / code > is zero, < code > @ctz< / code > returns < code > T.bit_count< / code > .
< / p >
2018-07-07 04:25:32 +00:00
{#see_also|@clz|@popCount#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@divExact#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @divExact(numerator: T, denominator: T) T< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
Exact division. Caller guarantees < code > denominator != 0< / code > and
< code > @divTrunc(numerator, denominator) * denominator == numerator< / code > .
< / p >
< ul >
< li > < code > @divExact(6, 3) == 2< / code > < / li >
< li > < code > @divExact(a, b) * b == a< / code > < / li >
< / ul >
2018-01-17 05:22:33 +00:00
< p > For a function that returns a possible error code, use < code > @import("std").math.divExact< / code > .< / p >
{#see_also|@divTrunc|@divFloor#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@divFloor#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @divFloor(numerator: T, denominator: T) T< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
Floored division. Rounds toward negative infinity. For unsigned integers it is
the same as < code > numerator / denominator< / code > . Caller guarantees < code > denominator != 0< / code > and
< code > !(@typeId(T) == builtin.TypeId.Int and T.is_signed and numerator == @minValue(T) and denominator == -1)< / code > .
< / p >
< ul >
< li > < code > @divFloor(-5, 3) == -2< / code > < / li >
< li > < code > @divFloor(a, b) + @mod(a, b) == a< / code > < / li >
< / ul >
2018-01-17 05:22:33 +00:00
< p > For a function that returns a possible error code, use < code > @import("std").math.divFloor< / code > .< / p >
{#see_also|@divTrunc|@divExact#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@divTrunc#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @divTrunc(numerator: T, denominator: T) T< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
Truncated division. Rounds toward zero. For unsigned integers it is
the same as < code > numerator / denominator< / code > . Caller guarantees < code > denominator != 0< / code > and
< code > !(@typeId(T) == builtin.TypeId.Int and T.is_signed and numerator == @minValue(T) and denominator == -1)< / code > .
< / p >
< ul >
< li > < code > @divTrunc(-5, 3) == -1< / code > < / li >
< li > < code > @divTrunc(a, b) + @rem(a, b) == a< / code > < / li >
< / ul >
2018-01-17 05:22:33 +00:00
< p > For a function that returns a possible error code, use < code > @import("std").math.divTrunc< / code > .< / p >
{#see_also|@divFloor|@divExact#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@embedFile#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @embedFile(comptime path: []const u8) [X]u8< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
This function returns a compile time constant fixed-size array with length
equal to the byte count of the file given by < code > path< / code > . The contents of the array
are the contents of the file.
< / p >
< p >
< code > path< / code > is absolute or relative to the current file, just like < code > @import< / code > .
< / 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 19:01:42 +00:00
2018-06-19 07:50:38 +00:00
{#header_open|@enumToInt#}
< pre > < code class = "zig" > @enumToInt(enum_value: var) var< / code > < / pre >
< p >
Converts an enumeration value into its integer tag type.
< / p >
{#see_also|@intToEnum#}
{#header_close#}
2018-06-18 19:01:42 +00:00
{#header_open|@errSetCast#}
< pre > < code class = "zig" > @errSetCast(comptime T: DestType, value: var) DestType< / code > < / pre >
2017-12-19 07:39:43 +00:00
< p >
2018-06-18 19:01:42 +00:00
Converts an error value from one error set to another error set. Attempting to convert an error
2018-06-18 22:48:29 +00:00
which is not in the destination error set results in safety-protected {#link|Undefined Behavior#}.
2017-12-19 07:39:43 +00:00
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 19:01:42 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@errorName#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @errorName(err: error) []u8< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
This function returns the string representation of an error. If an error
declaration is:
< / p >
< pre > < code class = "zig" > error OutOfMem< / code > < / pre >
< p >
Then the string representation is < code > "OutOfMem"< / code > .
< / p >
< p >
If there are no calls to < code > @errorName< / code > in an entire application,
or all calls have a compile-time known value for < code > err< / code > , then no
error name table will be generated.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 22:48:29 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@errorReturnTrace#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @errorReturnTrace() ?*builtin.StackTrace< / code > < / 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 19:01:42 +00:00
2018-06-18 22:48:29 +00:00
{#header_open|@errorToInt#}
< pre > < code class = "zig" > @errorToInt(err: var) @IntType(false, @sizeOf(error) * 8)< / code > < / pre >
< p >
Supports the following types:
< / p >
< ul >
< li > error unions< / li >
< li > < code > E!void< / code > < / li >
< / 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-06-18 19:01:42 +00:00
{#header_open|@export#}
< pre > < code class = "zig" > @export(comptime name: []const u8, target: var, linkage: builtin.GlobalLinkage) []const u8< / code > < / pre >
< p >
Creates a symbol in the output object file.
< / p >
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@fence#}
2017-11-07 08:22:27 +00:00
< pre > < code class = "zig" > @fence(order: AtomicOrder)< / code > < / pre >
< p >
The < code > fence< / code > function is used to introduce happens-before edges between operations.
< / p >
< p >
< code > AtomicOrder< / code > can be found with < code > @import("builtin").AtomicOrder< / code > .
< / 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 07:07:16 +00:00
{#header_open|@field#}
< pre > < code class = "zig" > @field(lhs: var, comptime field_name: []const u8) (field)< / code > < / pre >
< p > Preforms field access equivalent to < code > lhs.-& gtfield_name-& lt< / code > .< / p >
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@fieldParentPtr#}
2017-11-07 08:22:27 +00:00
< pre > < code class = "zig" > @fieldParentPtr(comptime ParentType: type, comptime field_name: []const u8,
2018-05-31 14:56:59 +00:00
field_ptr: *T) *ParentType< / code > < / 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 07:07:16 +00:00
{#header_open|@floatCast#}
< pre > < code class = "zig" > @floatCast(comptime DestType: type, value: var) DestType< / code > < / pre >
< 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#}
< pre > < code class = "zig" > @floatToInt(comptime DestType: type, float: var) DestType< / code > < / pre >
< p >
Converts the integer part of a floating point number to the destination type.
< / p >
2018-06-19 20:06:10 +00: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 07:07:16 +00:00
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@frameAddress#}
2017-11-07 08:22:27 +00:00
< pre > < code class = "zig" > @frameAddress()< / code > < / pre >
< 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-08-02 08:47:39 +00:00
{#header_open|@handle#}
< pre > < code class = "zig" > @handle()< / code > < / pre >
< p >
This function returns a < code > promise->T< / code > type, where < code > T< / code >
is the return type of the async function in scope.
< / p >
< p >
This function is only valid within an async function scope.
< / p >
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@import#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @import(comptime path: []u8) (namespace)< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
This function finds a zig file corresponding to < code > path< / code > and imports all the
public top level declarations into the resulting namespace.
< / p >
< p >
< code > path< / code > can be a relative or absolute path, or it can be the name of a package.
If it is a relative path, it is relative to the file that contains the < code > @import< / code >
function call.
< / p >
< p >
The following packages are always available:
< / p >
< ul >
< li > < code > @import("std")< / code > - Zig Standard Library< / li >
< li > < code > @import("builtin")< / code > - Compiler-provided types and variables< / li >
< / ul >
2018-01-17 05:22:33 +00:00
{#see_also|Compile Variables|@embedFile#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@inlineCall#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @inlineCall(function: X, args: ...) Y< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
This calls a function, in the same way that invoking an expression with parentheses does:
< / 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 "inline function call" {
assert(@inlineCall(add, 3, 9) == 12);
}
2018-01-25 09:10:11 +00:00
fn add(a: i32, b: i32) i32 { return a + b; }
2018-01-19 08:03:20 +00:00
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
Unlike a normal function call, however, < code > @inlineCall< / code > guarantees that the call
will be inlined. If the call cannot be inlined, a compile error is emitted.
< / p >
2018-01-17 05:22:33 +00:00
{#see_also|@noInlineCall#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 07:07:16 +00:00
{#header_open|@intCast#}
< pre > < code class = "zig" > @intCast(comptime DestType: type, int: var) DestType< / code > < / pre >
< 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 22:48:29 +00:00
safety-protected {#link|Undefined Behavior#}.
< / p >
{#header_close#}
2018-06-19 07:50:38 +00:00
{#header_open|@intToEnum#}
< pre > < code class = "zig" > @intToEnum(comptime DestType: type, int_value: @TagType(DestType)) DestType< / code > < / pre >
< 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 22:48:29 +00:00
{#header_open|@intToError#}
< pre > < code class = "zig" > @intToError(value: @IntType(false, @sizeOf(error) * 8)) error< / code > < / pre >
< p >
Converts from the integer representation of an error into the global error set type.
< / 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 07:07:16 +00:00
< / p >
2018-06-18 22:48:29 +00:00
{#see_also|@errorToInt#}
2018-06-18 07:07:16 +00:00
{#header_close#}
{#header_open|@intToFloat#}
< pre > < code class = "zig" > @intToFloat(comptime DestType: type, int: var) DestType< / code > < / pre >
< 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#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @intToPtr(comptime DestType: type, int: usize) DestType< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-01-23 04:06:07 +00:00
Converts an integer to a pointer. To convert the other way, use {#link|@ptrToInt#}.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 07:07:16 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@IntType#}
2018-07-16 14:53:15 +00:00
< pre > < code class = "zig" > @IntType(comptime is_signed: bool, comptime bit_count: u32) type< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
This function returns an integer type with the given signness and bit count.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@maxValue#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @maxValue(comptime T: type) (number literal)< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
This function returns the maximum value of the integer type < code > T< / code > .
< / p >
< p >
The result is a compile time constant.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@memberCount#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @memberCount(comptime T: type) (number literal)< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-02-01 01:56:53 +00:00
This function returns the number of members in a struct, enum, or union type.
2017-11-07 08:22:27 +00:00
< / p >
< p >
The result is a compile time constant.
< / p >
2018-02-01 01:56:53 +00:00
< p >
It does not include functions, variables, or constants.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@memberName#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @memberName(comptime T: type, comptime index: usize) [N]u8< / code > < / pre >
2018-02-01 01:56:53 +00:00
< p > Returns the field name of a struct, union, or enum.< / p >
< p >
The result is a compile time constant.
< / p >
< p >
It does not include functions, variables, or constants.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@memberType#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @memberType(comptime T: type, comptime index: usize) type< / code > < / pre >
2018-02-01 01:56:53 +00:00
< p > Returns the field type of a struct or union.< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@memcpy#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @memcpy(noalias dest: *u8, noalias source: *const u8, byte_count: usize)< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
This function copies bytes from one region of memory to another. < code > dest< / code > and
< code > source< / code > are both pointers and must not overlap.
< / 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 >
< pre > < code class = "zig" > for (source[0...byte_count]) |b, i| dest[i] = b;< / code > < / pre >
< 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 >
< pre > < code class = "zig" > const mem = @import("std").mem;
mem.copy(u8, dest[0...byte_count], source[0...byte_count]);< / code > < / pre >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@memset#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @memset(dest: *u8, c: u8, byte_count: usize)< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
This function sets a region of memory to < code > c< / code > . < code > dest< / code > is a pointer.
< / 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 >
2018-05-18 03:21:44 +00:00
< pre > < code class = "zig" > for (dest[0...byte_count]) |*b| b.* = c;< / code > < / 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 >
< pre > < code > const mem = @import("std").mem;
mem.set(u8, dest, c);< / code > < / pre >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@minValue#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @minValue(comptime T: type) (number literal)< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
This function returns the minimum value of the integer type T.
< / p >
< p >
The result is a compile time constant.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@mod#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @mod(numerator: T, denominator: T) T< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
Modulus division. For unsigned integers this is the same as
< code > numerator % denominator< / code > . Caller guarantees < code > denominator > 0< / code > .
< / p >
< ul >
< li > < code > @mod(-5, 3) == 1< / code > < / li >
< li > < code > @divFloor(a, b) + @mod(a, b) == a< / code > < / li >
< / ul >
2018-01-17 05:22:33 +00:00
< p > For a function that returns an error code, see < code > @import("std").math.mod< / code > .< / p >
{#see_also|@rem#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@mulWithOverflow#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @mulWithOverflow(comptime T: type, a: T, b: T, result: *T) bool< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-05-18 03:21:44 +00:00
Performs < code > result.* = a * b< / code > . If overflow or underflow occurs,
2017-11-07 08:22:27 +00:00
stores the overflowed bits in < code > result< / code > and returns < code > true< / code > .
If no overflow or underflow occurs, returns < code > false< / code > .
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-05-12 21:35:15 +00:00
{#header_open|@newStackCall#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @newStackCall(new_stack: []u8, function: var, args: ...) var< / code > < / pre >
2018-05-12 21:35:15 +00:00
< p >
This calls a function, in the same way that invoking an expression with parentheses does. However,
instead of using the same stack as the caller, the function uses the stack provided in the < code > new_stack< / code >
parameter.
< / p >
{#code_begin|test#}
const std = @import("std");
const assert = std.debug.assert;
var new_stack_bytes: [1024]u8 = undefined;
test "calling a function with a new stack" {
const arg = 1234;
const a = @newStackCall(new_stack_bytes[0..512], targetFunction, arg);
const b = @newStackCall(new_stack_bytes[512..], targetFunction, arg);
_ = targetFunction(arg);
assert(arg == 1234);
assert(a < b ) ;
}
fn targetFunction(x: i32) usize {
assert(x == 1234);
var local_variable: i32 = 42;
const ptr = &local_variable;
2018-05-18 03:21:44 +00:00
ptr.* += 1;
2018-05-12 21:35:15 +00:00
assert(local_variable == 43);
return @ptrToInt(ptr);
}
{#code_end#}
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@noInlineCall#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @noInlineCall(function: var, args: ...) var< / code > < / pre >
2018-01-03 08:27:48 +00:00
< p >
This calls a function, in the same way that invoking an expression with parentheses does:
< / p >
2018-05-12 21:35:15 +00:00
{#code_begin|test#}
const assert = @import("std").debug.assert;
2018-01-03 08:27:48 +00:00
test "noinline function call" {
assert(@noInlineCall(add, 3, 9) == 12);
}
2018-05-12 21:35:15 +00:00
fn add(a: i32, b: i32) i32 {
return a + b;
}
{#code_end#}
2018-01-03 08:27:48 +00:00
< p >
Unlike a normal function call, however, < code > @noInlineCall< / code > guarantees that the call
will not be inlined. If the call must be inlined, a compile error is emitted.
< / p >
2018-01-17 05:22:33 +00:00
{#see_also|@inlineCall#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@offsetOf#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @offsetOf(comptime T: type, comptime field_name: [] const u8) (number literal)< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
This function returns the byte offset of a field relative to its containing struct.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@OpaqueType#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @OpaqueType() type< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
Creates a new type with an unknown size and alignment.
< / p >
< p >
This is typically used for type safety when interacting with C code that does not expose struct details.
Example:
< / p >
2018-05-31 14:56:59 +00:00
{#code_begin|test_err|expected type '*Derp', found '*Wat'#}
2018-01-19 08:03:20 +00:00
const Derp = @OpaqueType();
2017-11-07 08:22:27 +00:00
const Wat = @OpaqueType();
2018-05-31 14:56:59 +00:00
extern fn bar(d: *Derp) void;
export fn foo(w: *Wat) void {
2017-11-07 08:22:27 +00:00
bar(w);
2018-01-19 08:03:20 +00:00
}
test "call foo" {
foo(undefined);
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@panic#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @panic(message: []const u8) noreturn< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
Invokes the panic handler function. By default the panic handler function
calls the public < code > panic< / code > function exposed in the root source file, or
if there is not one specified, invokes the one provided in < code > std/special/panic.zig< / code > .
< / p >
< p > Generally it is better to use < code > @import("std").debug.panic< / code > .
However, < code > @panic< / code > can be useful for 2 scenarios:
< / 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-07-07 04:25:32 +00:00
{#header_open|@popCount#}
< pre > < code class = "zig" > @popCount(integer: var) var< / code > < / pre >
< p > Counts the number of bits set in an integer.< / p >
< p >
If < code > integer< / code > is known at {#link|comptime#}, the return type is < code > comptime_int< / code > .
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-01-17 04:19:05 +00:00
{#header_open|@ptrCast#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @ptrCast(comptime DestType: type, value: var) DestType< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
Converts a pointer of one type to a pointer of another type.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@ptrToInt#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @ptrToInt(value: var) usize< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
Converts < code > value< / code > to a < code > usize< / code > which is the address of the pointer. < code > value< / code > can be one of these types:
< / p >
< ul >
2018-05-31 14:56:59 +00:00
< li > < code > *T< / code > < / li >
< li > < code > ?*T< / code > < / li >
2017-11-07 08:22:27 +00:00
< li > < code > fn()< / code > < / li >
< li > < code > ?fn()< / code > < / li >
< / 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#}
{#header_open|@rem#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @rem(numerator: T, denominator: T) T< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
Remainder division. For unsigned integers this is the same as
< code > numerator % denominator< / code > . Caller guarantees < code > denominator > 0< / code > .
< / p >
< ul >
< li > < code > @rem(-5, 3) == -2< / code > < / li >
< li > < code > @divTrunc(a, b) + @rem(a, b) == a< / code > < / li >
< / ul >
2018-01-17 05:22:33 +00:00
< p > For a function that returns an error code, see < code > @import("std").math.rem< / code > .< / p >
{#see_also|@mod#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@returnAddress#}
2017-11-07 08:22:27 +00:00
< pre > < code class = "zig" > @returnAddress()< / code > < / pre >
< p >
This function returns a pointer to the return address of the current stack
frame.
< / p >
< p >
The implications of this are target specific and not consistent across
all platforms.
< / p >
< p >
This function is only valid within function scope.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-03-15 01:51:06 +00:00
{#header_open|@setAlignStack#}
< pre > < code class = "zig" > @setAlignStack(comptime alignment: u29)< / code > < / pre >
< p >
Ensures that a function will have a stack alignment of at least < code > alignment< / code > bytes.
< / p >
{#header_close#}
2018-01-23 03:24:07 +00:00
{#header_open|@setCold#}
< pre > < code class = "zig" > @setCold(is_cold: bool)< / code > < / pre >
< p >
Tells the optimizer that a function is rarely called.
< / p >
{#header_close#}
2018-01-25 06:46:12 +00:00
{#header_open|@setRuntimeSafety#}
< pre > < code class = "zig" > @setRuntimeSafety(safety_on: bool)< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-01-25 06:46:12 +00:00
Sets whether runtime safety checks are on for the scope that contains the function call.
2017-11-07 08:22:27 +00:00
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@setEvalBranchQuota#}
2017-11-07 08:22:27 +00:00
< pre > < code class = "zig" > @setEvalBranchQuota(new_quota: usize)< / code > < / pre >
< 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 >
If the < code > new_quota< / code > is smaller than the default quota (< code > 1000< / code > ) or
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#}
< p > Now we use < code class = "zig" > @setEvalBranchQuota< / code > :< / p >
{#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#}
{#header_open|@setFloatMode#}
2017-11-07 08:22:27 +00:00
< pre > < code class = "zig" > @setFloatMode(scope, mode: @import("builtin").FloatMode)< / code > < / pre >
< p >
Sets the floating point mode for a given scope. Possible values are:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
pub const FloatMode = enum {
2017-11-07 08:22:27 +00:00
Optimized,
Strict,
2018-01-19 08:03:20 +00:00
};
{#code_end#}
2017-11-07 08:22:27 +00:00
< ul >
< li >
< code > Optimized< / code > (default) - Floating point operations may do all of the following:
< 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 >
< li >
< code > Strict< / code > - Floating point operations follow strict IEEE compliance.
< / li >
< / ul >
2018-01-17 05:22:33 +00:00
{#see_also|Floating Point Operations#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@setGlobalLinkage#}
2017-11-07 08:22:27 +00:00
< pre > < code class = "zig" > @setGlobalLinkage(global_variable_name, comptime linkage: GlobalLinkage)< / code > < / pre >
< p >
< code > GlobalLinkage< / code > can be found with < code > @import("builtin").GlobalLinkage< / code > .
< / p >
2018-01-17 05:22:33 +00:00
{#see_also|Compile Variables#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@shlExact#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @shlExact(value: T, shift_amt: Log2T) T< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
Performs the left shift operation (< code > < < < / code > ). Caller guarantees
that the shift will not shift any 1 bits out.
< / p >
< p >
The type of < code > shift_amt< / code > is an unsigned integer with < code > log2(T.bit_count)< / code > bits.
This is because < code > shift_amt > = T.bit_count< / code > is undefined behavior.
< / p >
2018-01-17 05:22:33 +00:00
{#see_also|@shrExact|@shlWithOverflow#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@shlWithOverflow#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @shlWithOverflow(comptime T: type, a: T, shift_amt: Log2T, result: *T) bool< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-05-18 03:21:44 +00:00
Performs < code > result.* = a < < b< / code > . If overflow or underflow occurs,
2017-11-07 08:22:27 +00:00
stores the overflowed bits in < code > result< / code > and returns < code > true< / code > .
If no overflow or underflow occurs, returns < code > false< / code > .
< / p >
< p >
The type of < code > shift_amt< / code > is an unsigned integer with < code > log2(T.bit_count)< / code > bits.
This is because < code > shift_amt > = T.bit_count< / code > is undefined behavior.
< / p >
2018-01-17 05:22:33 +00:00
{#see_also|@shlExact|@shrExact#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@shrExact#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @shrExact(value: T, shift_amt: Log2T) T< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
Performs the right shift operation (< code > > > < / code > ). Caller guarantees
that the shift will not shift any 1 bits out.
< / p >
< p >
The type of < code > shift_amt< / code > is an unsigned integer with < code > log2(T.bit_count)< / code > bits.
This is because < code > shift_amt > = T.bit_count< / code > is undefined behavior.
< / 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 21:25:29 +00:00
2018-01-17 04:19:05 +00:00
{#header_open|@sizeOf#}
2018-06-18 21:25:29 +00:00
< pre > < code class = "zig" > @sizeOf(comptime T: type) comptime_int< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
This function returns the number of bytes it takes to store < code > T< / code > in memory.
< / p >
< p >
The result is a target-specific compile time constant.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 21:25:29 +00:00
{#header_open|@sliceToBytes#}
< pre > < code class = "zig" > @sliceToBytes(value: var) []u8< / code > < / pre >
< p >
Converts a slice or array to a slice of < code > u8< / code > . The resulting slice has the same
{#link|pointer|Pointers#} properties as the parameter.
< / p >
{#header_close#}
2018-04-15 17:21:52 +00:00
{#header_open|@sqrt#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @sqrt(comptime T: type, value: T) T< / code > < / pre >
2018-04-15 17:21:52 +00:00
< p >
Performs the square root of a floating point number. Uses a dedicated hardware instruction
when available. Currently only supports f32 and f64 at runtime. f128 at runtime is TODO.
< / p >
< p >
This is a low-level intrinsic. Most code can use < code > std.math.sqrt< / code > instead.
< / p >
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|@subWithOverflow#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @subWithOverflow(comptime T: type, a: T, b: T, result: *T) bool< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
2018-05-18 03:21:44 +00:00
Performs < code > result.* = a - b< / code > . If overflow or underflow occurs,
2017-11-07 08:22:27 +00:00
stores the overflowed bits in < code > result< / code > and returns < code > true< / code > .
If no overflow or underflow occurs, returns < code > false< / code > .
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 07:07:16 +00:00
{#header_open|@tagName#}
< pre > < code class = "zig" > @tagName(value: var) []const u8< / code > < / pre >
< p >
Converts an enum value or union value to a slice of bytes representing the name.
< / p >
{#header_close#}
{#header_open|@TagType#}
< pre > < code class = "zig" > @TagType(T: type) type< / code > < / pre >
< 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-01-17 04:19:05 +00:00
{#header_open|@truncate#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @truncate(comptime T: type, integer) T< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
This function truncates bits from an integer type, resulting in a smaller
integer type.
< / p >
< p >
The following produces a crash in debug mode and undefined behavior in
release mode:
< / p >
< pre > < code class = "zig" > const a: u16 = 0xabcd;
const b: u8 = u8(a);< / code > < / pre >
< p >
However this is well defined and working code:
< / p >
< pre > < code class = "zig" > const a: u16 = 0xabcd;
const b: u8 = @truncate(u8, a);
// b is now 0xcd< / code > < / pre >
< 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#}
{#header_open|@typeId#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @typeId(comptime T: type) @import("builtin").TypeId< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
Returns which kind of type something is. Possible values:
< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|syntax#}
pub const TypeId = enum {
2017-11-07 08:22:27 +00:00
Type,
Void,
Bool,
NoReturn,
Int,
Float,
Pointer,
Array,
Struct,
2018-06-05 09:14:43 +00:00
ComptimeFloat,
ComptimeInt,
2018-06-05 09:54:11 +00:00
Undefined,
2018-06-05 09:30:01 +00:00
Null,
2018-06-10 03:42:14 +00:00
Optional,
2017-11-07 08:22:27 +00:00
ErrorUnion,
Error,
Enum,
Union,
Fn,
Namespace,
Block,
BoundFn,
ArgTuple,
Opaque,
2018-05-01 10:42:20 +00:00
};
{#code_end#}
{#header_close#}
{#header_open|@typeInfo#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @typeInfo(comptime T: type) @import("builtin").TypeInfo< / code > < / pre >
2018-05-01 10:42:20 +00:00
< p >
Returns information on the type. Returns a value of the following union:
< / p >
{#code_begin|syntax#}
pub const TypeInfo = union(TypeId) {
Type: void,
Void: void,
Bool: void,
NoReturn: void,
Int: Int,
Float: Float,
Pointer: Pointer,
Array: Array,
Struct: Struct,
2018-06-05 09:14:43 +00:00
ComptimeFloat: void,
ComptimeInt: void,
2018-06-05 09:54:11 +00:00
Undefined: void,
2018-06-05 09:30:01 +00:00
Null: void,
2018-06-10 03:42:14 +00:00
Optional: Optional,
2018-05-01 10:42:20 +00:00
ErrorUnion: ErrorUnion,
ErrorSet: ErrorSet,
Enum: Enum,
Union: Union,
Fn: Fn,
Namespace: void,
Block: void,
BoundFn: Fn,
ArgTuple: void,
Opaque: void,
Promise: Promise,
pub const Int = struct {
is_signed: bool,
bits: u8,
};
pub const Float = struct {
bits: u8,
};
pub const Pointer = struct {
2018-06-19 16:16:59 +00:00
size: Size,
2018-05-01 10:42:20 +00:00
is_const: bool,
is_volatile: bool,
alignment: u32,
child: type,
2018-06-19 16:16:59 +00:00
pub const Size = enum {
One,
Many,
Slice,
};
2018-05-01 10:42:20 +00:00
};
pub const Array = struct {
len: usize,
child: type,
};
pub const ContainerLayout = enum {
Auto,
Extern,
Packed,
};
pub const StructField = struct {
name: []const u8,
offset: ?usize,
field_type: type,
};
pub const Struct = struct {
layout: ContainerLayout,
fields: []StructField,
defs: []Definition,
};
2018-06-10 03:42:14 +00:00
pub const Optional = struct {
2018-05-01 10:42:20 +00:00
child: type,
};
pub const ErrorUnion = struct {
error_set: type,
payload: type,
};
pub const Error = struct {
name: []const u8,
value: usize,
};
pub const ErrorSet = struct {
errors: []Error,
};
pub const EnumField = struct {
name: []const u8,
value: usize,
};
pub const Enum = struct {
layout: ContainerLayout,
tag_type: type,
fields: []EnumField,
defs: []Definition,
};
pub const UnionField = struct {
name: []const u8,
enum_field: ?EnumField,
field_type: type,
};
pub const Union = struct {
layout: ContainerLayout,
2018-06-19 14:49:48 +00:00
tag_type: ?type,
2018-05-01 10:42:20 +00:00
fields: []UnionField,
defs: []Definition,
};
pub const CallingConvention = enum {
Unspecified,
C,
Cold,
Naked,
Stdcall,
Async,
};
pub const FnArg = struct {
is_generic: bool,
is_noalias: bool,
2018-06-19 14:45:19 +00:00
arg_type: ?type,
2018-05-01 10:42:20 +00:00
};
pub const Fn = struct {
calling_convention: CallingConvention,
is_generic: bool,
is_var_args: bool,
2018-06-19 14:45:19 +00:00
return_type: ?type,
async_allocator_type: ?type,
2018-05-01 10:42:20 +00:00
args: []FnArg,
};
pub const Promise = struct {
2018-06-19 14:45:19 +00:00
child: ?type,
2018-05-01 10:42:20 +00:00
};
pub const Definition = struct {
name: []const u8,
is_pub: bool,
data: Data,
pub const Data = union(enum) {
Type: type,
Var: type,
Fn: FnDef,
pub const FnDef = struct {
fn_type: type,
inline_type: Inline,
calling_convention: CallingConvention,
is_var_args: bool,
is_extern: bool,
is_export: bool,
lib_name: ?[]const u8,
return_type: type,
arg_names: [][] const u8,
pub const Inline = enum {
Auto,
Always,
Never,
};
};
};
};
2018-01-19 08:03:20 +00:00
};
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@typeName#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @typeName(T: type) []u8< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
This function returns the string representation of a type.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|@typeOf#}
2018-05-31 14:56:59 +00:00
< pre > < code class = "zig" > @typeOf(expression) type< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
This function returns a compile-time constant, which is the type of the
expression passed as an argument. The expression is evaluated.
< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_close#}
{#header_open|Build Mode#}
2017-11-07 08:22:27 +00:00
< p >
2018-06-14 22:12:05 +00: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 22:12:05 +00: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 02:03:51 +00: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 22:12:05 +00: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 22:12:05 +00:00
< li > Large binary size< / li >
2017-11-07 08:22:27 +00:00
< / ul >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|ReleaseFast#}
2018-01-19 08:03:20 +00:00
< pre > < code class = "shell" > $ zig build-exe example.zig --release-fast< / 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 22:12:05 +00:00
< li > Large binary size< / li >
2017-11-07 08:22:27 +00:00
< / ul >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|ReleaseSafe#}
2018-01-19 08:03:20 +00:00
< pre > < code class = "shell" > $ zig build-exe example.zig --release-safe< / 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 22:12:05 +00:00
< li > Large binary size< / li >
< / ul >
{#header_close#}
{#header_open|ReleaseSmall#}
< pre > < code class = "shell" > $ zig build-exe example.zig --release-small< / code > < / pre >
< ul >
< li > Medium runtime performance< / li >
< li > Safety checks disabled< / li >
< li > Slow compilation speed< / li >
< li > Small binary size< / li >
2017-11-07 08:22:27 +00:00
< / ul >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-14 22:12:05 +00:00
{#see_also|Compile Variables|Zig Build System|Undefined Behavior#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#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 19:01:42 +00: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
on a per-block basis with {#link|setRuntimeSafety#}. The {#link|ReleaseFast#}
2017-11-07 08:22:27 +00:00
build mode disables all safety checks in order to facilitate optimizations.
< / 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 19:49:49 +00: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 {
2017-11-07 08:22:27 +00:00
const array = "hello";
const garbage = array[5];
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 19:49:49 +00: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-01-19 08:03:20 +00:00
{#code_begin|test_err|attempt to cast negative value to unsigned integer#}
comptime {
2017-11-07 08:22:27 +00:00
const value: i32 = -1;
2018-06-17 06:57:07 +00:00
const unsigned = @intCast(u32, value);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 19:49:49 +00: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);
std.debug.warn("value: {}\n", unsigned);
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-07-02 19:49:49 +00:00
To obtain the maximum value of an unsigned integer, use {#link|@maxValue#}.
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 >
2018-01-19 08:03:20 +00:00
{#code_begin|test_err|cast from 'u16' to 'u8' truncates bits#}
comptime {
2017-11-07 08:22:27 +00:00
const spartan_count: u16 = 300;
2018-06-17 06:57:07 +00:00
const byte = @intCast(u8, spartan_count);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 19:49:49 +00: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);
std.debug.warn("value: {}\n", byte);
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
2018-07-02 19:49:49 +00: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 >
< li > < code > +< / code > (addition)< / li >
< li > < code > -< / code > (subtraction)< / li >
< li > < code > -< / code > (negation)< / li >
< li > < code > *< / code > (multiplication)< / li >
< li > < code > /< / code > (division)< / li >
2018-07-02 19:49:49 +00: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 19:49:49 +00:00
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
pub fn main() void {
var byte: u8 = 255;
byte += 1;
std.debug.warn("value: {}\n", byte);
}
{#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 >
< li > < code > @import("std").math.add< / code > < / li >
< li > < code > @import("std").math.sub< / code > < / li >
< li > < code > @import("std").math.mul< / code > < / li >
< li > < code > @import("std").math.divTrunc< / code > < / li >
< li > < code > @import("std").math.divFloor< / code > < / li >
< li > < code > @import("std").math.divExact< / code > < / li >
< li > < code > @import("std").math.shl< / code > < / li >
< / 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;
2017-11-07 08:22:27 +00:00
const warn = @import("std").debug.warn;
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| {
2017-11-07 08:22:27 +00:00
warn("unable to add one: {}\n", @errorName(err));
return err;
};
warn("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 >
These builtins return a < code > bool< / code > of whether or not overflow
occurred, as well as returning the overflowed bits:
< / p >
< ul >
2018-07-02 19:49:49 +00: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 19:49:49 +00: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#}
const warn = @import("std").debug.warn;
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)) {
2017-11-07 08:22:27 +00:00
warn("overflowed result: {}\n", result);
} else {
warn("result: {}\n", result);
}
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 >
< li > < code > +%< / code > (wraparound addition)< / li >
< li > < code > -%< / code > (wraparound subtraction)< / li >
< li > < code > -%< / code > (wraparound negation)< / li >
< li > < code > *%< / code > (wraparound multiplication)< / li >
< / ul >
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 "wraparound addition and subtraction" {
const x: i32 = @maxValue(i32);
const min_val = x +% 1;
assert(min_val == @minValue(i32));
const max_val = min_val -% 1;
assert(max_val == @maxValue(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 {
2017-11-07 08:22:27 +00:00
const x = @shlExact(u8(0b01010101), 2);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 19:49:49 +00: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);
std.debug.warn("value: {}\n", y);
}
{#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 {
2017-11-07 08:22:27 +00:00
const x = @shrExact(u8(0b10101010), 2);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 19:49:49 +00: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);
std.debug.warn("value: {}\n", y);
}
{#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 19:49:49 +00:00
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
2017-11-07 08:22:27 +00:00
2018-07-02 19:49:49 +00:00
pub fn main() void {
var a: u32 = 1;
var b: u32 = 0;
var c = a / b;
std.debug.warn("value: {}\n", c);
}
{#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 19:49:49 +00:00
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
2017-11-07 08:22:27 +00:00
2018-07-02 19:49:49 +00:00
pub fn main() void {
var a: u32 = 10;
var b: u32 = 0;
var c = a % b;
std.debug.warn("value: {}\n", c);
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Exact Division Remainder#}
2018-07-02 19:49:49 +00: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);
std.debug.warn("value: {}\n", c);
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Slice Widen Remainder#}
2018-07-02 19:49:49 +00:00
< p > At compile-time:< / p >
{#code_begin|test_err|unable to convert#}
comptime {
var bytes = [5]u8{ 1, 2, 3, 4, 5 };
var slice = @bytesToSlice(u32, bytes);
}
{#code_end#}
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
pub fn main() void {
var bytes = [5]u8{ 1, 2, 3, 4, 5 };
var slice = @bytesToSlice(u32, bytes[0..]);
std.debug.warn("value: {}\n", slice[0]);
}
{#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 03:42:14 +00:00
const optional_number: ?i32 = null;
const number = optional_number.?;
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 19:49:49 +00: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.?;
std.debug.warn("value: {}\n", number);
}
{#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
the < code > if< / code > expression:< / p >
2018-01-17 08:24:03 +00:00
{#code_begin|exe|test#}
const warn = @import("std").debug.warn;
2018-01-25 09:10:11 +00:00
pub fn main() void {
2018-06-10 03:42:14 +00:00
const optional_number: ?i32 = null;
2017-11-07 08:22:27 +00:00
2018-06-10 03:42:14 +00:00
if (optional_number) |number| {
2017-11-07 08:22:27 +00:00
warn("got number: {}\n", number);
} else {
warn("it's null\n");
}
2018-01-17 08:24:03 +00:00
}
{#code_end#}
2018-07-02 19:49:49 +00: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 19:49:49 +00:00
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
pub fn main() void {
const number = getNumberOrFail() catch unreachable;
std.debug.warn("value: {}\n", number);
}
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
the < code > if< / code > expression:< / p >
2018-01-19 08:03:20 +00:00
{#code_begin|exe#}
2018-01-17 08:24:03 +00:00
const warn = @import("std").debug.warn;
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| {
warn("got number: {}\n", number);
} else |err| {
warn("got error: {}\n", @errorName(err));
}
}
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 19:49:49 +00: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 22:48:29 +00:00
const number = @errorToInt(err) + 10;
const invalid_err = @intToError(number);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-07-02 19:49:49 +00: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);
std.debug.warn("value: {}\n", number);
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Invalid Enum Cast#}
2018-07-02 19:49:49 +00:00
< p > At compile-time:< / p >
{#code_begin|test_err|has no tag matching integer value 3#}
const Foo = enum {
A,
B,
C,
};
comptime {
const a: u2 = 3;
const b = @intToEnum(Foo, a);
}
{#code_end#}
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
const Foo = enum {
A,
B,
C,
};
2017-11-07 08:22:27 +00:00
2018-07-02 19:49:49 +00:00
pub fn main() void {
var a: u2 = 3;
var b = @intToEnum(Foo, a);
std.debug.warn("value: {}\n", @tagName(b));
}
{#code_end#}
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 19:01:42 +00:00
{#header_open|Invalid Error Set Cast#}
2018-07-09 15:13:29 +00:00
< p > At compile-time:< / p >
{#code_begin|test_err|error.B not a member of error set 'Set2'#}
const Set1 = error{
A,
B,
};
const Set2 = error{
A,
C,
};
comptime {
_ = @errSetCast(Set2, Set1.B);
}
{#code_end#}
< p > At runtime:< / p >
{#code_begin|exe_err#}
2018-07-10 14:37:58 +00:00
const std = @import("std");
2018-07-09 15:13:29 +00:00
const Set1 = error{
A,
B,
};
const Set2 = error{
A,
C,
};
pub fn main() void {
2018-07-10 14:37:58 +00:00
foo(Set1.B);
2018-07-09 15:13:29 +00:00
}
2018-07-10 14:37:58 +00:00
fn foo(set1: Set1) void {
const x = @errSetCast(Set2, set1);
std.debug.warn("value: {}\n", x);
2018-07-09 15:13:29 +00:00
}
{#code_end#}
2018-06-18 19:01:42 +00:00
{#header_close#}
2018-01-17 04:19:05 +00:00
{#header_open|Incorrect Pointer Alignment#}
2018-07-09 15:13:29 +00:00
< p > At compile-time:< / p >
{#code_begin|test_err|pointer address 0x1 is not aligned to 4 bytes#}
comptime {
const ptr = @intToPtr(*i32, 0x1);
const aligned = @alignCast(4, ptr);
}
{#code_end#}
< p > At runtime:< / p >
{#code_begin|exe_err#}
pub fn main() !void {
var array align(4) = []u32{ 0x11111111, 0x11111111 };
const bytes = @sliceToBytes(array[0..]);
if (foo(bytes) != 0x11111111) return error.Wrong;
}
fn foo(bytes: []u8) u32 {
const slice4 = bytes[1..5];
const int_slice = @bytesToSlice(u32, @alignCast(4, slice4));
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 14:37:58 +00:00
< p > At compile-time:< / p >
{#code_begin|test_err|accessing union field 'float' while field 'int' is set#}
comptime {
var f = Foo{ .int = 42 };
f.float = 12.34;
}
const Foo = union {
float: f32,
int: u32,
};
{#code_end#}
< p > At runtime:< / p >
{#code_begin|exe_err#}
const std = @import("std");
const Foo = union {
float: f32,
int: u32,
};
pub fn main() void {
var f = Foo{ .int = 42 };
bar(&f);
}
fn bar(f: *Foo) void {
f.float = 12.34;
std.debug.warn("value: {}\n", f.float);
}
{#code_end#}
< p >
This safety is not available for < code > extern< / code > or < code > packed< / code > unions.
< / p >
< p >
To change the active field of a union, assign the entire union, like this:
< / p >
{#code_begin|exe#}
const std = @import("std");
const Foo = union {
float: f32,
int: u32,
};
pub fn main() void {
var f = Foo{ .int = 42 };
bar(&f);
}
fn bar(f: *Foo) void {
f.* = Foo{ .float = 12.34 };
std.debug.warn("value: {}\n", f.float);
}
{#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");
const Foo = union {
float: f32,
int: u32,
};
pub fn main() void {
var f = Foo{ .int = 42 };
f = Foo{ .float = undefined };
bar(&f);
std.debug.warn("value: {}\n", f.float);
}
fn bar(f: *Foo) void {
f.float = 12.34;
}
{#code_end#}
2018-06-19 20:06:10 +00:00
{#header_close#}
2017-11-17 03:13:20 +00:00
2018-06-19 20:06:10 +00:00
{#header_open|Out of Bounds Float To Integer Cast#}
< p > TODO< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
2018-06-18 19:01:42 +00:00
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Memory#}
2017-11-07 08:22:27 +00:00
< p > TODO: explain no default allocator in zig< / p >
< p > TODO: show how to use the allocator interface< / p >
< p > TODO: mention debug allocator< / p >
< p > TODO: importance of checking for allocation failure< / p >
< p > TODO: mention overcommit and the OOM Killer< / p >
< p > TODO: mention recursion< / p >
2018-01-17 05:22:33 +00:00
{#see_also|Pointers#}
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 >
Compile variables are accessible by importing the < code > "builtin"< / code > package,
which the compiler makes available to every Zig source file. It contains
compile-time constants such as the current target, endianness, and release mode.
< / 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 >
Example of what is imported with < code > @import("builtin")< / code > :
< / p >
2018-06-07 23:10:45 +00: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#}
2017-11-07 08:22:27 +00:00
< p > TODO: basic usage< / p >
< p > TODO: lazy analysis< / p >
< p > TODO: --test-filter< / p >
< p > TODO: --test-name-prefix< / p >
< p > TODO: testing in releasefast and releasesafe mode. assert still works< / p >
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Zig Build System#}
2017-11-07 08:22:27 +00:00
< p > TODO: explain purpose, it's supposed to replace make/cmake< / p >
< p > TODO: example of building a zig executable< / p >
< p > TODO: example of building a C library< / p >
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 >
< li > < code > c_short< / code > < / li >
< li > < code > c_ushort< / code > < / li >
< li > < code > c_int< / code > < / li >
< li > < code > c_uint< / code > < / li >
< li > < code > c_long< / code > < / li >
< li > < code > c_ulong< / code > < / li >
< li > < code > c_longlong< / code > < / li >
< li > < code > c_ulonglong< / code > < / li >
< li > < code > c_longdouble< / code > < / li >
< li > < code > c_void< / code > < / li >
< / ul >
2018-01-17 05:22:33 +00:00
{#see_also|Primitive Types#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|C String Literals#}
2018-01-19 08:03:20 +00:00
{#code_begin|exe#}
{#link_libc#}
2018-06-04 05:09:15 +00:00
extern fn puts([*]const u8) void;
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
puts(c"this has a null terminator");
puts(
c\\and so
c\\does this
c\\multiline C string literal
);
2018-01-19 08:03:20 +00:00
}
{#code_end#}
2018-01-17 05:22:33 +00:00
{#see_also|String Literals#}
2018-01-17 04:19:05 +00:00
{#header_close#}
{#header_open|Import from C Header File#}
2017-11-07 08:22:27 +00:00
< p >
The < code > @cImport< / code > builtin function can be used
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 01:27:44 +00: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 {
2018-01-19 08:03:20 +00:00
_ = c.printf(c"hello\n");
}
{#code_end#}
2017-11-07 08:22:27 +00:00
< p >
The < code > @cImport< / code > function takes an expression as a parameter.
This expression is evaluated at compile-time and is used to control
preprocessor directives and include multiple .h files:
< / 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({
@cDefine("NDEBUG", builtin.mode == builtin.Mode.ReleaseFast);
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-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 02:11:14 +00: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 14:56:59 +00:00
pub fn build(b: *Builder) void {
2017-11-07 08:22:27 +00:00
const obj = b.addObject("base64", "base64.zig");
const exe = b.addCExecutable("test");
exe.addCompileFlags([][]const u8 {
"-std=c99",
});
exe.addSourceFile("test.c");
exe.addObject(obj);
exe.setOutputPath(".");
2018-01-19 08:03:20 +00:00
b.default_step.dependOn(&exe.step);
}
{#code_end#}
2018-06-07 23:10:45 +00:00
< p class = "file" > terminal< / p >
2018-01-19 08:03:20 +00:00
< pre > < code class = "shell" > $ zig build
2017-11-07 08:22:27 +00:00
$ ./test
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#}
{#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:
armv8_2a
armv8_1a
armv8
2018-01-19 08:03:20 +00:00
armv8r
2017-11-07 08:22:27 +00:00
armv8m_baseline
armv8m_mainline
armv7
armv7em
armv7m
armv7s
armv7k
2018-01-19 08:03:20 +00:00
armv7ve
2017-11-07 08:22:27 +00:00
armv6
armv6m
armv6k
armv6t2
armv5
armv5te
armv4t
armeb
aarch64
aarch64_be
avr
bpfel
bpfeb
hexagon
mips
mipsel
mips64
mips64el
msp430
2018-01-19 08:03:20 +00:00
nios2
2017-11-07 08:22:27 +00:00
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
tce
2018-01-19 08:03:20 +00:00
tcele
2017-11-07 08:22:27 +00:00
thumb
thumbeb
i386
x86_64 (native)
xcore
nvptx
nvptx64
le32
le64
amdil
amdil64
hsail
hsail64
2018-01-19 08:03:20 +00:00
spir
2017-11-07 08:22:27 +00:00
spir64
kalimbav3
kalimbav4
kalimbav5
shave
lanai
wasm32
wasm64
renderscript32
renderscript64
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
bitrig
aix
cuda
nvcl
amdhsa
ps4
elfiamcu
tvos
watchos
mesa3d
2018-01-19 08:03:20 +00:00
contiki
zen
2017-11-07 08:22:27 +00:00
Environments:
2018-01-19 08:03:20 +00:00
unknown
2017-11-07 08:22:27 +00:00
gnu (native)
gnuabi64
gnueabi
gnueabihf
gnux32
code16
eabi
eabihf
android
musl
musleabi
musleabihf
msvc
itanium
cygnus
amdopencl
2018-01-19 08:03:20 +00:00
coreclr
opencl< / code > < / pre >
2017-11-07 08:22:27 +00:00
< p >
The Zig Standard Library (< code > @import("std")< / code > ) has architecture, environment, and operating sytsem
2018-07-14 15:52:48 +00:00
abstractions, and thus takes additional work to support more platforms.
Not all standard library code requires operating system abstractions, however,
2017-11-07 08:22:27 +00:00
so things such as generic data structures work an all above platforms.
< / p >
2018-07-14 15:52:48 +00: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 >
< li > MacOS x86_64< / li >
< / 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
exercise the abilty to put an extra comma at the end.
< / 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 >
Roughly speaking: < code > camelCaseFunctionName< / code > , < code > TitleCaseTypeName< / code > ,
< code > snake_case_variable_name< / code > . More precisely:
< / p >
< ul >
< li >
If < code > x< / code > is a < code > struct< / code > (or an alias of a < code > struct< / code > ),
then < code > x< / code > should be < code > TitleCase< / code > .
< / li >
< li >
If < code > x< / code > otherwise identifies a type, < code > x< / code > should have < code > snake_case< / code > .
< / li >
< li >
If < code > x< / code > is callable, and < code > x< / code > 's return type is < code > type< / code > , then < code > x< / code > should be < code > TitleCase< / code > .
< / li >
< li >
If < code > x< / code > is otherwise callable, then < code > x< / code > should be < code > camelCase< / code > .
< / li >
< li >
Otherwise, < code > x< / code > should be < code > snake_case< / code > .
< / 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 >
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
< code > ENOENT< / code > , follow the established convention.
< / 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");
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;
const StructName = struct {};
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-01-19 08:03:20 +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
;
const XmlParser = struct {};
// 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 >
< 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 possbly the last line of the file).< / p >
2018-05-25 01:27:44 +00: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#}
2018-01-17 04:19:05 +00:00
{#header_open|Grammar#}
2018-01-19 08:03:20 +00:00
< pre > < code class = "nohighlight" > Root = many(TopLevelItem) EOF
2017-11-07 08:22:27 +00:00
2018-01-31 06:51:15 +00:00
TopLevelItem = CompTimeExpression(Block) | TopLevelDecl | TestDecl
2017-11-07 08:22:27 +00:00
TestDecl = "test" String Block
2017-12-18 14:59:57 +00:00
TopLevelDecl = option("pub") (FnDef | ExternDecl | GlobalVarDecl | UseDecl)
2017-11-07 08:22:27 +00:00
2017-12-19 06:19:49 +00:00
GlobalVarDecl = option("export") VariableDeclaration ";"
2017-11-07 08:22:27 +00:00
2017-12-19 06:19:49 +00:00
LocalVarDecl = option("comptime") VariableDeclaration
VariableDeclaration = ("var" | "const") Symbol option(":" TypeExpr) option("align" "(" Expression ")") option("section" "(" Expression ")") "=" Expression
2017-11-07 08:22:27 +00:00
ContainerMember = (ContainerField | FnDef | GlobalVarDecl)
2018-03-19 19:00:11 +00:00
ContainerField = Symbol option(":" PrefixOpExpression) option("=" PrefixOpExpression) ","
2017-11-07 08:22:27 +00:00
UseDecl = "use" Expression ";"
ExternDecl = "extern" option(String) (FnProto | VariableDeclaration) ";"
2018-03-22 20:56:03 +00:00
FnProto = option("nakedcc" | "stdcallcc" | "extern" | ("async" option("< " Expression "> "))) "fn" option(Symbol) ParamDeclList option("align" "(" Expression ")") option("section" "(" Expression ")") option("!") (TypeExpr | "var")
2017-11-07 08:22:27 +00:00
2017-12-19 06:19:49 +00:00
FnDef = option("inline" | "export") FnProto Block
2017-11-07 08:22:27 +00:00
ParamDeclList = "(" list(ParamDecl, ",") ")"
2018-03-06 23:24:49 +00:00
ParamDecl = option("noalias" | "comptime") option(Symbol ":") (TypeExpr | "var" | "...")
2017-11-07 08:22:27 +00:00
2017-12-22 05:50:30 +00:00
Block = option(Symbol ":") "{" many(Statement) "}"
2017-11-07 08:22:27 +00:00
2017-12-21 03:55:24 +00:00
Statement = LocalVarDecl ";" | Defer(Block) | Defer(Expression) ";" | BlockExpression(Block) | Expression ";" | ";"
2017-11-07 08:22:27 +00:00
2018-03-19 19:00:11 +00:00
TypeExpr = (PrefixOpExpression "!" PrefixOpExpression) | PrefixOpExpression
2017-11-07 08:22:27 +00:00
BlockOrExpression = Block | Expression
2018-03-01 03:18:48 +00:00
Expression = TryExpression | ReturnExpression | BreakExpression | AssignmentExpression | CancelExpression | ResumeExpression
2017-11-07 08:22:27 +00:00
AsmExpression = "asm" option("volatile") "(" String option(AsmOutput) ")"
AsmOutput = ":" list(AsmOutputItem, ",") option(AsmInput)
AsmInput = ":" list(AsmInputItem, ",") option(AsmClobbers)
AsmOutputItem = "[" Symbol "]" String "(" (Symbol | "-> " TypeExpr) ")"
AsmInputItem = "[" Symbol "]" String "(" Expression ")"
AsmClobbers= ":" list(String, ",")
2018-06-10 03:42:14 +00:00
UnwrapExpression = BoolOrExpression (UnwrapOptional | UnwrapError) | BoolOrExpression
2017-11-07 08:22:27 +00:00
2018-06-10 05:13:51 +00:00
UnwrapOptional = "orelse" Expression
2017-11-07 08:22:27 +00:00
2018-01-07 22:28:20 +00:00
UnwrapError = "catch" option("|" Symbol "|") Expression
2017-11-07 08:22:27 +00:00
AssignmentExpression = UnwrapExpression AssignmentOperator UnwrapExpression | UnwrapExpression
AssignmentOperator = "=" | "*=" | "/=" | "%=" | "+=" | "-=" | "< < =" | "> > =" | "& =" | "^=" | "|=" | "*%=" | "+%=" | "-%="
2018-02-26 05:04:11 +00:00
BlockExpression(body) = Block | IfExpression(body) | IfErrorExpression(body) | TestExpression(body) | WhileExpression(body) | ForExpression(body) | SwitchExpression | CompTimeExpression(body) | SuspendExpression(body)
2017-11-07 08:22:27 +00:00
CompTimeExpression(body) = "comptime" body
SwitchExpression = "switch" "(" Expression ")" "{" many(SwitchProng) "}"
SwitchProng = (list(SwitchItem, ",") | "else") "=> " option("|" option("*") Symbol "|") Expression ","
SwitchItem = Expression | (Expression "..." Expression)
2017-12-21 03:55:24 +00:00
ForExpression(body) = option(Symbol ":") option("inline") "for" "(" Expression ")" option("|" option("*") Symbol option("," Symbol) "|") body option("else" BlockExpression(body))
2017-11-07 08:22:27 +00:00
BoolOrExpression = BoolAndExpression "or" BoolOrExpression | BoolAndExpression
2018-01-07 21:51:46 +00:00
ReturnExpression = "return" option(Expression)
TryExpression = "try" Expression
2017-11-07 08:22:27 +00:00
2018-02-26 05:04:11 +00:00
AwaitExpression = "await" Expression
2017-12-21 03:55:24 +00:00
BreakExpression = "break" option(":" Symbol) option(Expression)
2017-11-07 08:22:27 +00:00
2018-02-20 05:05:38 +00:00
CancelExpression = "cancel" Expression;
2018-03-01 03:18:48 +00:00
ResumeExpression = "resume" Expression;
2018-01-24 04:08:09 +00:00
Defer(body) = ("defer" | "deferror") body
2017-11-07 08:22:27 +00:00
IfExpression(body) = "if" "(" Expression ")" body option("else" BlockExpression(body))
2018-07-29 08:19:36 +00:00
SuspendExpression(body) = "suspend" option( body )
2018-02-26 05:04:11 +00:00
2018-01-07 21:51:46 +00:00
IfErrorExpression(body) = "if" "(" Expression ")" option("|" option("*") Symbol "|") body "else" "|" Symbol "|" BlockExpression(body)
2017-11-07 08:22:27 +00:00
TestExpression(body) = "if" "(" Expression ")" option("|" option("*") Symbol "|") body option("else" BlockExpression(body))
2017-12-21 03:55:24 +00:00
WhileExpression(body) = option(Symbol ":") option("inline") "while" "(" Expression ")" option("|" option("*") Symbol "|") option(":" "(" Expression ")") body option("else" option("|" Symbol "|") BlockExpression(body))
2017-11-07 08:22:27 +00:00
BoolAndExpression = ComparisonExpression "and" BoolAndExpression | ComparisonExpression
ComparisonExpression = BinaryOrExpression ComparisonOperator BinaryOrExpression | BinaryOrExpression
ComparisonOperator = "==" | "!=" | "< " | "> " | "< =" | "> ="
BinaryOrExpression = BinaryXorExpression "|" BinaryOrExpression | BinaryXorExpression
BinaryXorExpression = BinaryAndExpression "^" BinaryXorExpression | BinaryAndExpression
BinaryAndExpression = BitShiftExpression "& " BinaryAndExpression | BitShiftExpression
BitShiftExpression = AdditionExpression BitShiftOperator BitShiftExpression | AdditionExpression
2018-03-17 15:17:07 +00:00
BitShiftOperator = "< < " | "> > "
2017-11-07 08:22:27 +00:00
AdditionExpression = MultiplyExpression AdditionOperator AdditionExpression | MultiplyExpression
AdditionOperator = "+" | "-" | "++" | "+%" | "-%"
MultiplyExpression = CurlySuffixExpression MultiplyOperator MultiplyExpression | CurlySuffixExpression
CurlySuffixExpression = TypeExpr option(ContainerInitExpression)
2018-02-02 23:13:32 +00:00
MultiplyOperator = "||" | "*" | "/" | "%" | "**" | "*%"
2017-11-07 08:22:27 +00:00
2018-03-19 19:00:11 +00:00
PrefixOpExpression = PrefixOp TypeExpr | SuffixOpExpression
2017-11-07 08:22:27 +00:00
2018-06-10 03:42:14 +00:00
SuffixOpExpression = ("async" option("< " SuffixOpExpression "> ") SuffixOpExpression FnCallExpression) | PrimaryExpression option(FnCallExpression | ArrayAccessExpression | FieldAccessExpression | SliceExpression | ".*" | ".?")
2017-11-07 08:22:27 +00:00
FieldAccessExpression = "." Symbol
FnCallExpression = "(" list(Expression, ",") ")"
ArrayAccessExpression = "[" Expression "]"
SliceExpression = "[" Expression ".." option(Expression) "]"
ContainerInitExpression = "{" ContainerInitBody "}"
ContainerInitBody = list(StructLiteralField, ",") | list(Expression, ",")
StructLiteralField = "." Symbol "=" Expression
2018-06-10 03:42:14 +00:00
PrefixOp = "!" | "-" | "~" | (("*" | "[*]") option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "-%" | "try" | "await"
2017-11-07 08:22:27 +00:00
2018-03-24 23:25:53 +00:00
PrimaryExpression = Integer | Float | String | CharLiteral | KeywordLiteral | GroupedExpression | BlockExpression(BlockOrExpression) | Symbol | ("@" Symbol FnCallExpression) | ArrayType | FnProto | AsmExpression | ContainerDecl | ("continue" option(":" Symbol)) | ErrorSetDecl | PromiseType
PromiseType = "promise" option("-> " TypeExpr)
2017-11-07 08:22:27 +00:00
ArrayType : "[" option(Expression) "]" option("align" "(" Expression option(":" Integer ":" Integer) ")")) option("const") option("volatile") TypeExpr
GroupedExpression = "(" Expression ")"
2018-02-26 05:04:11 +00:00
KeywordLiteral = "true" | "false" | "null" | "undefined" | "error" | "this" | "unreachable" | "suspend"
2017-11-07 08:22:27 +00:00
2018-01-31 06:51:15 +00:00
ErrorSetDecl = "error" "{" list(Symbol, ",") "}"
2017-12-04 01:43:56 +00:00
ContainerDecl = option("extern" | "packed")
("struct" option(GroupedExpression) | "union" option("enum" option(GroupedExpression) | GroupedExpression) | ("enum" option(GroupedExpression)))
"{" many(ContainerMember) "}"< / 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 >
< li > Minimize energy spent on coding style.< / li >
< li > Together we serve end users.< / li >
< / ul >
2018-01-17 04:19:05 +00:00
{#header_close#}
2017-11-07 08:22:27 +00:00
< / div >
2018-01-19 08:03:20 +00:00
< script >
/*! highlight.js v9.12.0 | BSD3 License | git.io/hljslicense */
!function(e){var n="object"==typeof window& & window||"object"==typeof self&&self; "undefined"!=typeof exports?e(exports):n& & (n.hljs=e({}),"function"==typeof define& & define.amd& & define([],function(){return n.hljs}))}(function(e){function n(e){return e.replace(/&/g,"& ").replace(/< /g,"< ").replace(/>/g,"> ")}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n); return t& & 0===t.index}function a(e){return k.test(e)}function i(e){var n,t,r,i,o=e.className+" ";if(o+=e.parentNode?e.parentNode.className:"",t=B.exec(o))return w(t[1])?t[1]:"no-highlight";for(o=o.split(/\s+/),n=0,r=o.length;r>n;n++)if(i=o[n],a(i)||w(i))return i}function o(e){var n,t={},r=Array.prototype.slice.call(arguments,1);for(n in e)t[n]=e[n];return r.forEach(function(e){for(n in e)t[n]=e[n]}),t}function u(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3===i.nodeType?a+=i.nodeValue.length:1===i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i})); return a}(e,0),n}function c(e,r,a){function i(){return e.length& & r.length?e[0].offset!==r[0].offset?e[0].offset< r [ 0 ] . offset ? e:r: " start " = = = r [ 0 ] . event ? e:r:e . length ? e:r } function o ( e ) { function r ( e ) { return " " + e . nodeName + ' = " ' + n ( e . value ) . replace ( ' " ' , " & quot ; " ) + ' " ' } s + = " < " + t ( e ) + E . map . call ( e . attributes , r ) . join ( " " ) + " > "}function u(e){s+="< /"+t(e)+">"}function c(e){("start"===e.event?o:u)(e.node)}for(var l=0,s="",f=[];e.length||r.length;){var g=i();if(s+=n(a.substring(l,g[0].offset)),l=g[0].offset,g===e){f.reverse().forEach(u);do c(g.splice(0,1)[0]),g=i();while(g===e&&g.length&&g[0].offset===l); f.reverse().forEach(o)}else"start"===g[0].event?f.push(g[0].node):f.pop(),c(g.splice(0,1)[0])}return s+n(a.substr(l))}function l(e){return e.v& & !e.cached_variants& & (e.cached_variants=e.v.map(function(n){return o(e,{v:null},n)})),e.cached_variants||e.eW& & [o(e)]||[e]}function s(e){function n(e){return e& & e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var o={},u=function(n,t){e.cI& & (t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");o[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?u("keyword",a.k):x(a.k).forEach(function(e){u(e,a.k[e])}),a.k=o}a.lR=t(a.l||/\w+/,!0),i& & (a.bK& & (a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.e||a.eW||(a.e=/\B|\b/),a.e& & (a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW& & i.tE& & (a.tE+=(a.e?"|":"")+i.tE)),a.i& & (a.iR=t(a.i)),null==a.r& & (a.r=1),a.c||(a.c=[]),a.c=Array.prototype.concat.apply([],a.c.map(function(e){return l("self"===e?a:e)})),a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i); var c=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=c.length?t(c.join("|"),!0):{exec:function(){return null}}}}r(e)}function f(e,t,a,i){function o(e,n){var t,a;for(t=0,a=n.c.length;a>t;t++)if(r(n.c[t].bR,e))return n.c[t]}function u(e,n){if(r(e.eR,n)){for(;e.endsParent&&e.parent; )e=e.parent;return e}return e.eW?u(e.parent,n):void 0}function c(e,n){return!a& & r(n.iR,e)}function l(e,n){var t=N.cI?n[0].toLowerCase():n[0];return e.k.hasOwnProperty(t)& & e.k[t]}function p(e,n,t,r){var a=r?"":I.classPrefix,i='< span class = "'+a,o=t?" " :C ; return i + = e + ' " > ',i+n+o}function h(){var e,t,r,a;if(!E.k)return n(k);for(a="",t=0,E.lR.lastIndex=0,r=E.lR.exec(k);r;)a+=n(k.substring(t,r.index)),e=l(E,r),e?(B+=e[1],a+=p(e[0],n(r[0]))):a+=n(r[0]),t=E.lR.lastIndex,r=E.lR.exec(k);return a+n(k.substr(t))}function d(){var e="string"==typeof E.sL;if(e& & !y[E.sL])return n(k);var t=e?f(E.sL,k,!0,x[E.sL]):g(k,E.sL.length?E.sL:void 0);return E.r>0& & (B+=t.r),e& & (x[E.sL]=t.top),p(t.language,t.value,!1,!0)}function b(){L+=null!=E.sL?d():h(),k=""}function v(e){L+=e.cN?p(e.cN,"",!0):"",E=Object.create(e,{parent:{value:E}})}function m(e,n){if(k+=e,null==n)return b(),0;var t=o(n,E);if(t)return t.skip?k+=n:(t.eB&&(k+=n),b(),t.rB||t.eB||(k=n)),v(t,n),t.rB?0:n.length; var r=u(E,n);if(r){var a=E;a.skip?k+=n:(a.rE||a.eE||(k+=n),b(),a.eE& & (k=n)
< / script >
< script >
hljs.registerLanguage("zig", function(t) {
var e = {
cN: "keyword",
b: "\\b[a-z\\d_]*_t\\b"
},
r = {
cN: "string",
v: [{
b: '(u8?|U)?L?"',
e: '"',
i: "\\n",
c: [t.BE]
}, {
b: '(u8?|U)?R"',
e: '"',
c: [t.BE]
}, {
b: "'\\\\?.",
e: "'",
i: "."
}]
},
s = {
cN: "number",
v: [{
b: "\\b(0b[01']+)"
}, {
b: "(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"
}, {
b: "(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"
}],
r: 0
},
i = {
cN: "meta",
b: /#\s*[a-z]+\b/,
e: /$/,
k: {
"meta-keyword": "zzzzzzdisable"
},
c: [{
b: /\\\n/,
r: 0
}, t.inherit(r, {
cN: "meta-string"
}), {
cN: "meta-string",
b: /< [^\n>]*>/,
e: /$/,
i: "\\n"
}, t.CLCM, t.CBCM]
},
a = t.IR + "\\s*\\(",
c = {
2018-06-11 21:38:24 +00:00
keyword: "const align var extern stdcallcc nakedcc volatile export pub noalias inline struct packed enum union break return try catch test continue unreachable comptime and or asm defer errdefer if else switch while for fn use bool f32 f64 void type noreturn error i8 u8 i16 u16 i32 u32 i64 u64 isize usize i8w u8w i16w i32w u32w i64w u64w isizew usizew c_short c_ushort c_int c_uint c_long c_ulong c_longlong c_ulonglong resume cancel await async orelse",
2018-07-07 04:25:32 +00:00
built_in: "atomicLoad breakpoint returnAddress frameAddress fieldParentPtr setFloatMode IntType OpaqueType compileError compileLog setCold setRuntimeSafety setEvalBranchQuota offsetOf memcpy inlineCall setGlobalLinkage divTrunc divFloor enumTagName intToPtr ptrToInt panic ptrCast intCast floatCast intToFloat floatToInt boolToInt bytesToSlice sliceToBytes errSetCast bitCast rem mod memset sizeOf alignOf alignCast maxValue minValue memberCount memberName memberType typeOf addWithOverflow subWithOverflow mulWithOverflow shlWithOverflow shlExact shrExact cInclude cDefine cUndef ctz clz popCount import cImport errorName embedFile cmpxchgStrong cmpxchgWeak fence divExact truncate atomicRmw sqrt field typeInfo typeName newStackCall errorToInt intToError enumToInt intToEnum",
2018-01-19 08:03:20 +00:00
literal: "true false null undefined"
},
n = [e, t.CLCM, t.CBCM, s, r];
return {
aliases: ["c", "cc", "h", "c++", "h++", "hpp"],
k: c,
i: "< /",
c: n.concat([i, {
b: "\\b(deque|list|queue|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*< ",
e: ">",
k: c,
c: ["self", e]
}, {
b: t.IR + "::",
k: c
}, {
v: [{
b: /=/,
e: /;/
}, {
b: /\(/,
e: /\)/
}, {
bK: "new throw return else",
e: /;/
}],
k: c,
c: n.concat([{
b: /\(/,
e: /\)/,
k: c,
c: n.concat(["self"]),
r: 0
}]),
r: 0
}, {
cN: "function",
b: "(" + t.IR + "[\\*& \\s]+)+" + a,
rB: !0,
e: /[{;=]/,
eE: !0,
k: c,
i: /[^\w\s\*& ]/,
c: [{
b: a,
rB: !0,
c: [t.TM],
r: 0
}, {
cN: "params",
b: /\(/,
e: /\)/,
k: c,
r: 0,
c: [t.CLCM, t.CBCM, r, s, e]
}, t.CLCM, t.CBCM, i]
}, {
cN: "class",
bK: "class struct",
e: /[{;:]/,
c: [{
b: /< /,
e: />/,
c: ["self"]
}, t.TM]
}]),
exports: {
preprocessor: i,
strings: r,
k: c
}
}
});
hljs.initHighlightingOnLoad();
< / script >
2017-11-07 08:22:27 +00:00
< / body >
< / html >