Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/04-working-with-c/08-c-pointers.md | # C Pointers
Up until now, we have used the following kinds of pointers:
- single item pointers - `*T`
- many item pointers - `[*]T`
- slices - `[]T`
Unlike the aforementioned pointers, C pointers cannot deal with specially
aligned data and may point to the address `0`. C pointers coerce back and forth
between integers, and also coerce to single and multi item pointers. When a C
pointer of value `0` is coerced to a non-optional pointer, this is detectable
illegal behaviour.
Outside of automatically translated C code, the usage of `[*c]` is almost always
a bad idea, and should almost never be used.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/04-working-with-c/04-extern-structs.md | # Extern Structs
Normal structs in Zig do not have a defined layout; `extern` structs are
required for when you want the layout of your struct to match the layout of your
C ABI.
Let's create an extern struct. This test should be run with `x86_64` with a
`gnu` ABI, which can be done with `-target x86_64-native-gnu`.
```zig
const expect = @import("std").testing.expect;
const Data = extern struct { a: i32, b: u8, c: f32, d: bool, e: bool };
test "hmm" {
const x = Data{
.a = 10005,
.b = 42,
.c = -10.5,
.d = false,
.e = true,
};
const z = @as([*]const u8, @ptrCast(&x));
try expect(@as(*const i32, @ptrCast(@alignCast(z))).* == 10005);
try expect(@as(*const u8, @ptrCast(@alignCast(z + 4))).* == 42);
try expect(@as(*const f32, @ptrCast(@alignCast(z + 8))).* == -10.5);
try expect(@as(*const bool, @ptrCast(@alignCast(z + 12))).* == false);
try expect(@as(*const bool, @ptrCast(@alignCast(z + 13))).* == true);
}
```
This is what the memory inside our `x` value looks like.
| Field | a | a | a | a | b | | | | c | c | c | c | d | e | | |
| ----- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |
| Bytes | 15 | 27 | 00 | 00 | 2A | 00 | 00 | 00 | 00 | 00 | 28 | C1 | 00 | 01 | 00 | 00 |
Note how there are gaps in the middle and at the end - this is called "padding".
The data in this padding is undefined memory, and won't always be zero.
As our `x` value is that of an extern struct, we could safely pass it into a C
function expecting a `Data`, providing the C function was also compiled with the
same `gnu` ABI and CPU arch.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/04-working-with-c/10-c-import.md | # cImport
Zig's [`@cImport`](https://ziglang.org/documentation/master/#cImport) builtin is
unique in that it takes in an expression, which can only take in
[`@cInclude`](https://ziglang.org/documentation/master/#cInclude),
[`@cDefine`](https://ziglang.org/documentation/master/#cDefine), and
[`@cUndef`](https://ziglang.org/documentation/master/#cUndef). This works
similarly to translate-c, translating C code to Zig under the hood.
[`@cInclude`](https://ziglang.org/documentation/master/#cInclude) takes in a
path string and adds the path to the includes list.
[`@cDefine`](https://ziglang.org/documentation/master/#cDefine) and
[`@cUndef`](https://ziglang.org/documentation/master/#cUndef) define and
undefine things for the import.
These three functions work exactly as you'd expect them to work within C code.
Similar to [`@import`](https://ziglang.org/documentation/master/#import), this
returns a struct type with declarations. It is typically recommended to only use
one instance of [`@cImport`](https://ziglang.org/documentation/master/#cImport)
in an application to avoid symbol collisions; the types generated within one
cImport will not be equivalent to those generated in another.
cImport is only available when linking libc.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/04-working-with-c/07-bit-aligned-pointers.md | # Bit Aligned Pointers
Similar to aligned pointers, bit-aligned pointers have extra information in
their type, which informs how to access the data. These are necessary when the
data is not byte-aligned. Bit alignment information is often needed to address
fields inside of packed structs.
```zig
test "bit aligned pointers" {
var x = MovementState{
.running = false,
.crouching = false,
.jumping = false,
.in_air = false,
};
const running = &x.running;
running.* = true;
const crouching = &x.crouching;
crouching.* = true;
try expect(@TypeOf(running) == *align(1:0:1) bool);
try expect(@TypeOf(crouching) == *align(1:1:1) bool);
try expect(@import("std").meta.eql(x, .{
.running = true,
.crouching = true,
.jumping = false,
.in_air = false,
}));
}
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/04-working-with-c/05-alignment.md | # Alignment
For circuitry reasons, CPUs access primitive values at specific multiples in
memory. This could mean, for example, that the address of an `f32` value must be
a multiple of 4, meaning `f32` has an alignment of 4. This so-called "natural
alignment" of primitive data types depends on CPU architecture. All alignments
are powers of 2.
Data of a larger alignment also has the alignment of every smaller alignment;
for example, a value which has an alignment of 16 also has an alignment of 8, 4,
2 and 1.
We can make specially aligned data by using the `align(x)` property. Here we are
making data with a greater alignment.
```zig
const a1: u8 align(8) = 100;
const a2 align(8) = @as(u8, 100);
```
And making data with a lesser alignment. Note: Creating data of a lesser
alignment isn't particularly useful.
```zig
const b1: u64 align(1) = 100;
const b2 align(1) = @as(u64, 100);
```
Like `const`, `align` is also a property of pointers.
```zig
test "aligned pointers" {
const a: u32 align(8) = 5;
try expect(@TypeOf(&a) == *align(8) const u32);
}
```
Let's make use of a function expecting an aligned pointer.
```zig
fn total(a: *align(64) const [64]u8) u32 {
var sum: u32 = 0;
for (a) |elem| sum += elem;
return sum;
}
test "passing aligned data" {
const x align(64) = [_]u8{10} ** 64;
try expect(total(&x) == 640);
}
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/04-working-with-c/11-linking-libc.md | # Linking libc
Linking libc can be done via the command line via `-lc`, or via `build.zig`
using `exe.linkLibC();`. The libc used is that of the compilation's target; Zig
provides libc for many targets.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/04-working-with-c/01-abi.md | ---
pagination_prev: build-system/generating-documentation
---
# ABI
An ABI _(application binary interface)_ is a standard, pertaining to:
- The in-memory layout of types (i.e. a type's size, alignment, offsets, and the
layouts of its fields)
- The in-linker naming of symbols (e.g. name mangling)
- The calling conventions of functions (i.e. how a function call works at a
binary level)
By defining these rules and not breaking them, an ABI is said to be stable, and
this can be used to, for example, reliably link together multiple libraries,
executables, or objects which were compiled separately (potentially on different
machines or using different compilers). This allows for FFI _(foreign function
interface)_ to take place, where we can share code between programming
languages.
Zig natively supports C ABIs for `extern` things; which C ABI is used depends on
the target you are compiling for (e.g. CPU architecture, operating system). This
allows for near-seamless interoperation with code that was not written in Zig;
the usage of C ABIs is standard amongst programming languages.
Zig internally does not use an ABI, meaning code should explicitly conform to a
C ABI where reproducible and defined binary-level behaviour is needed.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/04-working-with-c/09-translate-c.md | # Translate-C
Zig provides the command `zig translate-c` for automatic translation from C
source code.
Create the file `main.c` with the following contents.
```c
#include <stddef.h>
void int_sort(int* array, size_t count) {
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
if (array[j] > array[j+1]) {
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
```
Run the command `zig translate-c main.c` to get the equivalent Zig code output
to your console (stdout). You may wish to pipe this into a file with
`zig translate-c main.c > int_sort.zig` (warning for Windows users: piping in
PowerShell will produce a file with the incorrect encoding - use your editor to
correct this).
In another file you could use `@import("int_sort.zig")` to use this function.
Currently the code produced may be unnecessarily verbose, though translate-c
successfully translates most C code into Zig. You may wish to use translate-c to
produce Zig code before editing it into more idiomatic code; a gradual transfer
from C to Zig within a codebase is a supported use case.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/00-getting-started/04.running-tests-success.zig | const std = @import("std");
const expect = std.testing.expect;
test "always succeeds" {
try expect(true);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/00-getting-started/01-welcome.mdx | ---
slug: /
description: Get started with the Zig programming language. Zig is a general-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
pagination_prev: null
---
# Welcome
[Zig](https://ziglang.org) is a general-purpose programming language and
toolchain for maintaining **robust**, **optimal**, and **reusable** software.
:::warning
The latest release of Zig is 0.13.0 and is currently unstable.
:::
To follow this guide, we assume you have:
- Prior experience programming
- Some understanding of low-level programming concepts
Knowing a language like C, C++, Rust, Go, Pascal, or similar will help you follow
this guide. You must have an editor, terminal, and internet connection available
to you.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/00-getting-started/_category_.json | {
"label": "Getting Started",
"link": {
"description": "zig.guide - A Guide & Tutorial for the Zig programming language. Install and get started with ziglang here."
}
} |
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/00-getting-started/02-installation.mdx | ---
description: Installation instructions for the Zig programming language on Linux, Windows, and macOS.
---
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
# Installation
<Tabs
defaultValue="linux"
values={[
{label: 'Linux', value: 'linux'},
{label: 'Windows', value: 'windows'},
{label: 'macOS', value: 'macos'},
]}>
<TabItem value="linux">
Consider getting Zig from your distribution's [package manager](https://github.com/ziglang/zig/wiki/Install-Zig-from-a-Package-Manager). Most major linux distros package the latest Zig release.
### Installing manually
1. [Download](https://ziglang.org/download/#release-0.12.0) a prebuilt version of Zig.
Choose a build of Zig 0.12 for Linux that matches your CPU architecture. If you're unsure which architecture you're using, this can be found with:
```bash
uname -m
```
2. Extract the archive using tar, e.g.
```bash
tar xf zig-linux-x86_64-0.12.0.tar.xz
```
3. Add the location of your Zig binary to your path, e.g.
```bash
echo 'export PATH="$HOME/zig-linux-x86_64-0.12.0:$PATH"' >> ~/.bashrc
```
</TabItem>
<TabItem value="windows">
Consider getting Zig from a package manager such as [chocolatey](https://chocolatey.org/), [scoop](https://scoop.sh/), or [winget](https://learn.microsoft.com/en-us/windows/package-manager/winget/#install-winget).
All commands shown are to be used inside Powershell.
```powershell
choco install zig
```
```
winget install zig.zig
```
```
scoop install zig
```
### Installing manually
1. [Download](https://ziglang.org/download/#release-0.12.0) a prebuilt version of Zig.
Choose a build of Zig 0.12 for Windows that matches your CPU architecture. Most Windows systems use `x86_64`, also known as `AMD64`. If you're unsure which architecture you're using, this can be found with:
```powershell
$Env:PROCESSOR_ARCHITECTURE
```
2. Extract Zig.
3. Add Zig to your path:
<Tabs
defaultValue="user"
values={[
{label: 'Current User', value: 'user'},
{label: 'System Wide', value: 'system'},
]}>
<TabItem value="user">
```powershell
[Environment]::SetEnvironmentVariable(
"Path",
[Environment]::GetEnvironmentVariable("Path", "User") + ";C:\_\zig-windows-_",
"User"
)
```
</TabItem>
<TabItem value="system">
```powershell
[Environment]::SetEnvironmentVariable(
"Path",
[Environment]::GetEnvironmentVariable("Path", "Machine") + ";C:\_\zig-windows-_",
"Machine"
)
```
</TabItem>
</Tabs>
Close your terminal and create a new one.
</TabItem>
<TabItem value="macos">
Consider getting Zig from a package manager such as [brew](https://brew.sh/).
```
brew install zig
```
</TabItem>
</Tabs>
### Verifying your install
Verify your installation with `zig version`. The output should look like this:
```
$ zig version
0.12.0
```
### Extras
For completions and go-to-definition in your editor, consider installing the [Zig Language Server](https://github.com/zigtools/zls/#installation).
Consider joining a [Zig community](https://github.com/ziglang/zig/wiki/Community).
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/00-getting-started/03-hello-world.mdx | ---
description: Write your first program using the Zig programming language.
---
# Hello World
Create a file called `main.zig`, with the following contents:
```zig
const std = @import("std");
pub fn main() void {
std.debug.print("Hello, {s}!\n", .{"World"});
}
```
Use `zig run main.zig` to build and run it. In this example, `Hello, World!`
will be written to stderr, and is assumed to never fail.
:::warning found 'invalid bytes'
Make sure your `main.zig` file is UTF-8 encoded as the Zig compiler does not currently support other encodings. To re-encode your file as UTF-8, run `zig fmt main.zig` and reopen the file in your editor.
:::
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/00-getting-started/04-running-tests.mdx | ---
pagination_next: language-basics/assignment
---
import CodeBlock from "@theme/CodeBlock";
import Success from "!!raw-loader!./04.running-tests-success.zig";
# Running Tests
In this guide, code examples are often given as runnable tests. Before proceeding, make sure that you can run them successfully.
### Success
Save the following text as `test_pass.zig`, and run `zig test test_pass.zig`; you should read `All 1 tests passed.` in your terminal.
<CodeBlock language="zig">{Success}</CodeBlock>
:::note
Some code examples in this guide will have their imports at the top hidden, make sure to get them by clicking the copy button on the top-right of the code block.
:::
### Failure
Now, save the following text as `test_fail.zig` and observe it fail.
```zig
const std = @import("std");
const expect = std.testing.expect;
test "always fails" {
try expect(false);
}
```
Which should output something like:
```
Test [1/1] test.always fails... FAIL (TestUnexpectedResult)
/usr/lib/zig/std/testing.zig:515:14: 0x2241ef in expect (test)
if (!ok) return error.TestUnexpectedResult;
^
[...]/test_fail:5:5: 0x224305 in test.always fails (test)
try expect(false);
^
0 passed; 0 skipped; 1 failed.
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/05-async/_category_.json | {
"label": "Async",
"link": {
"description": "Details on how Zig's async features work."
}
} |
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/05-async/02-suspend-resume.md | # Suspend / Resume
In the previous section we talked of how async functions can give control back
to the caller, and how the async function can later take control back. This
functionality is provided by the keywords
[`suspend`, and `resume`](https://ziglang.org/documentation/master/#Suspend-and-Resume).
When a function suspends, control flow returns to wherever it was last resumed;
when a function is called via an `async` invocation, this is an implicit resume.
The comments in these examples indicate the order of execution. There are a few
things to take in here:
- The `async` keyword is used to invoke functions in an async context.
- `async func()` returns the function's frame.
- We must store this frame.
- The `resume` keyword is used on the frame, whereas `suspend` is used from the
called function.
This example has a suspend, but no matching resume.
```zig
const expect = @import("std").testing.expect;
var foo: i32 = 1;
test "suspend with no resume" {
var frame = async func(); //1
_ = frame;
try expect(foo == 2); //4
}
fn func() void {
foo += 1; //2
suspend {} //3
foo += 1; //never reached!
}
```
In well formed code, each suspend is matched with a resume.
```zig
var bar: i32 = 1;
test "suspend with resume" {
var frame = async func2(); //1
resume frame; //4
try expect(bar == 3); //6
}
fn func2() void {
bar += 1; //2
suspend {} //3
bar += 1; //5
}
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/05-async/03-async-await.md | # Async / Await
Similar to how well formed code has a suspend for every resume, each `async`
function invocation with a return value must be matched with an `await`. The
value yielded by `await` on the async frame corresponds to the function's
return.
You may notice that `func3` here is a normal function (i.e. it has no suspend
points - it is not an async function). Despite this, `func3` can work as an
async function when called from an async invocation; the calling convention of
`func3` doesn't have to be changed to async - `func3` can be of any calling
convention.
```zig
fn func3() u32 {
return 5;
}
test "async / await" {
var frame = async func3();
try expect(await frame == 5);
}
```
Using `await` on an async frame of a function which may suspend is only possible
from async functions. As such, functions that use `await` on the frame of an
async function are also considered async functions. If you can be sure that the
potential suspend doesn't happen, `nosuspend await` will stop this from
happening.
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/05-async/01-introduction.md | ---
pagination_prev: working-with-c/zig-cc
---
# Introduction
:::danger
Zig's async features have regressed in the compiler and are not present in the 0.11
Zig release, and they will likely not be featured in Zig 0.12 either.
:::
A functioning understanding of Zig's async requires familiarity with the concept
of the call stack. If you have not heard of this before,
[check out the wikipedia page](https://en.wikipedia.org/wiki/Call_stack).
<!-- TODO: actually explain the call stack? -->
A traditional function call comprises of three things:
1. Initiate the called function with its arguments, pushing the function's stack
frame
2. Transfer control to the function
3. Upon function completion, hand control back to the caller, retrieving the
function's return value and popping the function's stack frame
With Zig's async functions we can do more than this, with the transfer of
control being an ongoing two-way conversation (i.e. we can give control to the
function and take it back multiple times). Because of this, special
considerations must be made when calling a function in an async context; we can
no longer push and pop the stack frame as normal (as the stack is volatile, and
things "above" the current stack frame may be overwritten), instead explicitly
storing the async function's frame. While most people won't make use of its full
feature set, this style of async is useful for creating more powerful constructs
such as event loops.
The style of Zig's async may be described as suspendible stackless coroutines.
Zig's async is very different to something like an OS thread which has a stack,
and can only be suspended by the kernel. Furthermore, Zig's async is there to
provide you with control flow structures and code generation; async does not
imply parallelism or the usage of threads.
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/05-async/04-nosuspend.md | # Nosuspend
When calling a function which is determined to be async (i.e. it may suspend)
without an `async` invocation, the function which called it is also treated as
being async. When a function of a concrete (non-async) calling convention is
determined to have suspend points, this is a compile error as async requires its
own calling convention. This means, for example, that main cannot be async.
<!--no_test-->
```zig
pub fn main() !void {
suspend {}
}
```
(compiled from windows)
```
C:\zig\lib\zig\std\start.zig:165:1: error: function with calling convention 'Stdcall' cannot be async
fn WinStartup() callconv(.Stdcall) noreturn {
^
C:\zig\lib\zig\std\start.zig:173:65: note: async function call here
std.os.windows.kernel32.ExitProcess(initEventLoopAndCallMain());
^
C:\zig\lib\zig\std\start.zig:276:12: note: async function call here
return @call(.{ .modifier = .always_inline }, callMain, .{});
^
C:\zig\lib\zig\std\start.zig:334:37: note: async function call here
const result = root.main() catch |err| {
^
.\main.zig:12:5: note: suspends here
suspend {}
^
```
If you want to call an async function without using an `async` invocation, and
without the caller of the function also being async, the `nosuspend` keyword
comes in handy. This allows the caller of the async function to not also be
async, by asserting that the potential suspends do not happen.
<!--no_test-->
```zig
const std = @import("std");
fn doTicksDuration(ticker: *u32) i64 {
const start = std.time.milliTimestamp();
while (ticker.* > 0) {
suspend {}
ticker.* -= 1;
}
return std.time.milliTimestamp() - start;
}
pub fn main() !void {
var ticker: u32 = 0;
const duration = nosuspend doTicksDuration(&ticker);
}
```
In the above code if we change the value of `ticker` to be above 0, this is
detectable illegal behaviour. If we run that code, we will have an error like
this in safe build modes. Similar to other illegal behaviours in Zig, having
these happen in unsafe modes will result in undefined behaviour.
```
async function called in nosuspend scope suspended
.\main.zig:16:47: 0x7ff661dd3414 in main (main.obj)
const duration = nosuspend doTicksDuration(&ticker);
^
C:\zig\lib\zig\std\start.zig:173:65: 0x7ff661dd18ce in std.start.WinStartup (main.obj)
std.os.windows.kernel32.ExitProcess(initEventLoopAndCallMain());
^
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/05-async/06-basic-event-loop.md | # Basic Event Loop Implementation
An event loop is a design pattern in which events are dispatched and/or waited
upon. This will mean some kind of service or runtime that resumes suspended
async frames when conditions are met. This is the most powerful and useful use
case of Zig's async.
Here we will implement a basic event loop. This one will allow us to submit
tasks to be executed in a given amount of time. We will use this to submit pairs
of tasks which will print the time since the program's start. Here is an example
of the output.
```
[task-pair b] it is now 499 ms since start!
[task-pair a] it is now 1000 ms since start!
[task-pair b] it is now 1819 ms since start!
[task-pair a] it is now 2201 ms since start!
```
Here is the implementation.
<!--no_test-->
```zig
const std = @import("std");
// used to get monotonic time, as opposed to wall-clock time
var timer: ?std.time.Timer = null;
fn nanotime() u64 {
if (timer == null) {
timer = std.time.Timer.start() catch unreachable;
}
return timer.?.read();
}
// holds the frame, and the nanotime of
// when the frame should be resumed
const Delay = struct {
frame: anyframe,
expires: u64,
};
// suspend the caller, to be resumed later by the event loop
fn waitForTime(time_ms: u64) void {
suspend timer_queue.add(Delay{
.frame = @frame(),
.expires = nanotime() + (time_ms * std.time.ns_per_ms),
}) catch unreachable;
}
fn waitUntilAndPrint(
time1: u64,
time2: u64,
name: []const u8,
) void {
const start = nanotime();
// suspend self, to be woken up when time1 has passed
waitForTime(time1);
std.debug.print(
"[{s}] it is now {} ms since start!\n",
.{ name, (nanotime() - start) / std.time.ns_per_ms },
);
// suspend self, to be woken up when time2 has passed
waitForTime(time2);
std.debug.print(
"[{s}] it is now {} ms since start!\n",
.{ name, (nanotime() - start) / std.time.ns_per_ms },
);
}
fn asyncMain() void {
// stores the async frames of our tasks
var tasks = [_]@Frame(waitUntilAndPrint){
async waitUntilAndPrint(1000, 1200, "task-pair a"),
async waitUntilAndPrint(500, 1300, "task-pair b"),
};
// |*t| is used, as |t| would be a *const @Frame(...)
// which cannot be awaited upon
for (tasks) |*t| await t;
}
// priority queue of tasks
// lower .expires => higher priority => to be executed before
var timer_queue: std.PriorityQueue(Delay, void, cmp) = undefined;
fn cmp(context: void, a: Delay, b: Delay) std.math.Order {
_ = context;
return std.math.order(a.expires, b.expires);
}
pub fn main() !void {
timer_queue = std.PriorityQueue(Delay, void, cmp).init(
std.heap.page_allocator, undefined
);
defer timer_queue.deinit();
var main_task = async asyncMain();
// the body of the event loop
// pops the task which is to be next executed
while (timer_queue.removeOrNull()) |delay| {
// wait until it is time to execute next task
const now = nanotime();
if (now < delay.expires) {
std.time.sleep(delay.expires - now);
}
// execute next task
resume delay.frame;
}
nosuspend await main_task;
}
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/05-async/05-frames-suspend.md | # Async Frames, Suspend Blocks
`@Frame(function)` returns the frame type of the function. This works for async
functions, and functions without a specific calling convention.
```zig
fn add(a: i32, b: i32) i64 {
return a + b;
}
test "@Frame" {
var frame: @Frame(add) = async add(1, 2);
try expect(await frame == 3);
}
```
[`@frame()`](https://ziglang.org/documentation/master/#frame) returns a pointer
to the frame of the current function. Similar to `suspend` points, if this call
is found in a function then it is inferred as being async. All pointers to
frames coerce to the special type `anyframe`, which you can use `resume` upon.
This allows us to, for example, write a function that resumes itself.
```zig
fn double(value: u8) u9 {
suspend {
resume @frame();
}
return value * 2;
}
test "@frame 1" {
var f = async double(1);
try expect(nosuspend await f == 2);
}
```
Or, more interestingly, we can use it to tell other functions to resume us. Here
we're introducing **suspend blocks**. Upon entering a suspend block, the async
function is already considered suspended (i.e. it can be resumed). This means
that we can have our function resumed by something other than the last resumer.
```zig
const std = @import("std");
fn callLater(comptime laterFn: fn () void, ms: u64) void {
suspend {
wakeupLater(@frame(), ms);
}
laterFn();
}
fn wakeupLater(frame: anyframe, ms: u64) void {
std.time.sleep(ms * std.time.ns_per_ms);
resume frame;
}
fn alarm() void {
std.debug.print("Time's Up!\n", .{});
}
test "@frame 2" {
nosuspend callLater(alarm, 1000);
}
```
Using the `anyframe` data type can be thought of as a kind of type erasure, in
that we are no longer sure of the concrete type of the function or the function
frame. This is useful as it still allows us to resume the frame - in a lot of
code we will not care about the details and will just want to resume it. This
gives us a single concrete type which we can use for our async logic.
The natural drawback of `anyframe` is that we have lost type information, and we
no longer know what the return type of the function is. This means we cannot
await an `anyframe`. Zig's solution to this is the `anyframe->T` types, where
the `T` is the return type of the frame.
```zig
fn zero(comptime x: anytype) x {
return 0;
}
fn awaiter(x: anyframe->f32) f32 {
return nosuspend await x;
}
test "anyframe->T" {
var frame = async zero(f32);
try expect(awaiter(&frame) == 0);
}
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/08-crypto.md | # Crypto
[`std.crypto`](https://ziglang.org/documentation/master/std/#std.crypto)
includes many cryptographic utilities, including:
- AES (Aes128, Aes256)
- Diffie-Hellman key exchange (x25519)
- Elliptic-curve arithmetic (curve25519, edwards25519, ristretto255)
- Crypto secure hashing (blake2, Blake3, Gimli, Md5, sha1, sha2, sha3)
- MAC functions (Ghash, Poly1305)
- Stream ciphers (ChaCha20IETF, ChaCha20With64BitNonce, XChaCha20IETF, Salsa20,
XSalsa20)
This list is inexhaustive. For more in-depth information, try
[A tour of std.crypto in Zig 0.7.0 - Frank Denis](https://www.youtube.com/watch?v=9t6Y7KoCvyk).
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/05.formatting-array-print.zig | // hide-start
const std = @import("std");
const expect = std.testing.expect;
const eql = std.mem.eql;
const test_allocator = std.testing.allocator;
// hide-end
test "array printing" {
const string = try std.fmt.allocPrint(
test_allocator,
"{any} + {any} = {any}",
.{
@as([]const u8, &[_]u8{ 1, 4 }),
@as([]const u8, &[_]u8{ 2, 5 }),
@as([]const u8, &[_]u8{ 3, 9 }),
},
);
defer test_allocator.free(string);
try expect(eql(
u8,
string,
"{ 1, 4 } + { 2, 5 } = { 3, 9 }",
));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/05.formatting-print.zig | // hide-start
const std = @import("std");
const expect = std.testing.expect;
const eql = std.mem.eql;
const test_allocator = std.testing.allocator;
// hide-end
test "print" {
var list = std.ArrayList(u8).init(test_allocator);
defer list.deinit();
try list.writer().print(
"{} + {} = {}",
.{ 9, 10, 19 },
);
try expect(eql(u8, list.items, "9 + 10 = 19"));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/11-stacks.md | # Stacks
[`std.ArrayList`](https://ziglang.org/documentation/master/std/#std.ArrayList)
provides the methods necessary to use it as a stack. Here's an example of
creating a list of matched brackets.
```zig
test "stack" {
const string = "(()())";
var stack = std.ArrayList(usize).init(
test_allocator,
);
defer stack.deinit();
const Pair = struct { open: usize, close: usize };
var pairs = std.ArrayList(Pair).init(
test_allocator,
);
defer pairs.deinit();
for (string, 0..) |char, i| {
if (char == '(') try stack.append(i);
if (char == ')')
try pairs.append(.{
.open = stack.pop(),
.close = i,
});
}
for (pairs.items, 0..) |pair, i| {
try expect(std.meta.eql(pair, switch (i) {
0 => Pair{ .open = 1, .close = 2 },
1 => Pair{ .open = 3, .close = 4 },
2 => Pair{ .open = 0, .close = 5 },
else => unreachable,
}));
}
}
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/03-filesystem.mdx | import CodeBlock from "@theme/CodeBlock";
import CwdCreate from "!!raw-loader!./03.filesystem-cwd-create.zig";
import Stat from "!!raw-loader!./03.filesystem-stat.zig";
import MakeDirIterable from "!!raw-loader!./03.filesystem-make-dir-iterable.zig";
# Filesystem
Let's create and open a file in our current working directory, write to it, and
then read from it. Here we have to use `.seekTo` to go back to the start of the
file before reading what we have written.
<CodeBlock language="zig">{CwdCreate}</CodeBlock>
The functions
[`std.fs.openFileAbsolute`](https://ziglang.org/documentation/master/std/#std.fs.openFileAbsolute)
and similar absolute functions exist, but we will not test them here.
We can get various information about files by using `.stat()` on them. `Stat`
also contains fields for .inode and .mode, but they are not tested here as they
rely on the current OS' types.
<CodeBlock language="zig">{Stat}</CodeBlock>
We can make directories and iterate over their contents. Here we will use an
iterator (discussed later). This directory (and its contents) will be deleted
after this test finishes.
<CodeBlock language="zig">{MakeDirIterable}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/_category_.json | {
"label": "Standard Library",
"link": {
"description": "Zig's standard library in detail."
}
} |
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/04.readers-and-writers-reader.zig | // hide-start
const std = @import("std");
const expect = std.testing.expect;
const eql = std.mem.eql;
const test_allocator = std.testing.allocator;
// hide-end
test "io reader usage" {
const message = "Hello File!";
const file = try std.fs.cwd().createFile(
"junk_file2.txt",
.{ .read = true },
);
defer file.close();
try file.writeAll(message);
try file.seekTo(0);
const contents = try file.reader().readAllAlloc(
test_allocator,
message.len,
);
defer test_allocator.free(contents);
try expect(eql(u8, contents, message));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/10-hashmaps.md | # Hash Maps
The standard library provides
[`std.AutoHashMap`](https://ziglang.org/documentation/master/std/#std.AutoHashMap),
which lets you easily create a hash map type from a key type and a value type.
These must be initiated with an allocator.
Let's put some values in a hash map.
```zig
test "hashing" {
const Point = struct { x: i32, y: i32 };
var map = std.AutoHashMap(u32, Point).init(
test_allocator,
);
defer map.deinit();
try map.put(1525, .{ .x = 1, .y = -4 });
try map.put(1550, .{ .x = 2, .y = -3 });
try map.put(1575, .{ .x = 3, .y = -2 });
try map.put(1600, .{ .x = 4, .y = -1 });
try expect(map.count() == 4);
var sum = Point{ .x = 0, .y = 0 };
var iterator = map.iterator();
while (iterator.next()) |entry| {
sum.x += entry.value_ptr.x;
sum.y += entry.value_ptr.y;
}
try expect(sum.x == 10);
try expect(sum.y == -10);
}
```
`.fetchPut` puts a value in the hash map, returning a value if there was
previously a value for that key.
```zig
test "fetchPut" {
var map = std.AutoHashMap(u8, f32).init(
test_allocator,
);
defer map.deinit();
try map.put(255, 10);
const old = try map.fetchPut(255, 100);
try expect(old.?.value == 10);
try expect(map.get(255).? == 100);
}
```
[`std.StringHashMap`](https://ziglang.org/documentation/master/std/#std.StringHashMap)
is also provided for when you need strings as keys.
```zig
test "string hashmap" {
var map = std.StringHashMap(enum { cool, uncool }).init(
test_allocator,
);
defer map.deinit();
try map.put("loris", .uncool);
try map.put("me", .cool);
try expect(map.get("me").? == .cool);
try expect(map.get("loris").? == .uncool);
}
```
[`std.StringHashMap`](https://ziglang.org/documentation/master/std/#std.StringHashMap)
and
[`std.AutoHashMap`](https://ziglang.org/documentation/master/std/#std.AutoHashMap)
are just wrappers for
[`std.HashMap`](https://ziglang.org/documentation/master/std/#std.HashMap). If
these two do not fulfil your needs, using
[`std.HashMap`](https://ziglang.org/documentation/master/std/#std.HashMap)
directly gives you much more control.
If having your elements backed by an array is wanted behaviour, try
[`std.ArrayHashMap`](https://ziglang.org/documentation/master/std/#std.ArrayHashMap)
and its wrapper
[`std.AutoArrayHashMap`](https://ziglang.org/documentation/master/std/#std.AutoArrayHashMap).
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/04.readers-and-writers-custom.zig | // hide-start
const std = @import("std");
const expect = std.testing.expect;
const eql = std.mem.eql;
// hide-end
// Don't create a type like this! Use an
// arraylist with a fixed buffer allocator
const MyByteList = struct {
data: [100]u8 = undefined,
items: []u8 = &[_]u8{},
const Writer = std.io.Writer(
*MyByteList,
error{EndOfBuffer},
appendWrite,
);
fn appendWrite(
self: *MyByteList,
data: []const u8,
) error{EndOfBuffer}!usize {
if (self.items.len + data.len > self.data.len) {
return error.EndOfBuffer;
}
std.mem.copy(
u8,
self.data[self.items.len..],
data,
);
self.items = self.data[0 .. self.items.len + data.len];
return data.len;
}
fn writer(self: *MyByteList) Writer {
return .{ .context = self };
}
};
test "custom writer" {
var bytes = MyByteList{};
_ = try bytes.writer().write("Hello");
_ = try bytes.writer().write(" Writer!");
try expect(eql(u8, bytes.items, "Hello Writer!"));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/01-allocators.mdx | ---
pagination_prev: language-basics/imports
---
import CodeBlock from "@theme/CodeBlock";
import AllocatorsAlloc from "!!raw-loader!./01.allocators-alloc.zig";
import AllocatorsFba from "!!raw-loader!./01.allocators-fba.zig";
import AllocatorsArena from "!!raw-loader!./01.allocators-arena.zig";
import AllocatorsCreate from "!!raw-loader!./01.allocators-create.zig";
import AllocatorsGpa from "!!raw-loader!./01.allocators-gpa.zig";
# Allocators
The Zig standard library provides a pattern for allocating memory, which allows
the programmer to choose precisely how memory allocations are done within the
standard library - no allocations happen behind your back in the standard
library.
The most basic allocator is
[`std.heap.page_allocator`](https://ziglang.org/documentation/master/std/#std.heap.page_allocator).
Whenever this allocator makes an allocation, it will ask your OS for entire
pages of memory; an allocation of a single byte will likely reserve multiple
kibibytes. As asking the OS for memory requires a system call, this is also
extremely inefficient for speed.
Here, we allocate 100 bytes as a `[]u8`. Notice how defer is used in conjunction
with a free - this is a common pattern for memory management in Zig.
<CodeBlock language="zig">{AllocatorsAlloc}</CodeBlock>
The
[`std.heap.FixedBufferAllocator`](https://ziglang.org/documentation/master/std/#std.heap.FixedBufferAllocator)
is an allocator that allocates memory into a fixed buffer and does not make any
heap allocations. This is useful when heap usage is not wanted, for example,
when writing a kernel. It may also be considered for performance reasons. It
will give you the error `OutOfMemory` if it has run out of bytes.
<CodeBlock language="zig">{AllocatorsFba}</CodeBlock>
[`std.heap.ArenaAllocator`](https://ziglang.org/documentation/master/std/#std.heap.ArenaAllocator)
takes in a child allocator and allows you to allocate many times and only free
once. Here, `.deinit()` is called on the arena, which frees all memory. Using
`allocator.free` in this example would be a no-op (i.e. does nothing).
<CodeBlock language="zig">{AllocatorsArena}</CodeBlock>
`alloc` and `free` are used for slices. For single items, consider using
`create` and `destroy`.
<CodeBlock language="zig">{AllocatorsCreate}</CodeBlock>
The Zig standard library also has a general purpose allocator. This is a safe
allocator which can prevent double-free, use-after-free and can detect leaks.
Safety checks and thread safety can be turned off via its configuration struct
(left empty below). Zig's GPA is designed for safety over performance, but may
still be many times faster than page_allocator.
<CodeBlock language="zig">{AllocatorsGpa}</CodeBlock>
For high performance (but very few safety features!),
[`std.heap.c_allocator`](https://ziglang.org/documentation/master/std/#std.heap.c_allocator)
may be considered. This,however, has the disadvantage of requiring linking Libc,
which can be done with `-lc`.
Benjamin Feng's talk
[_What's a Memory Allocator Anyway?_](https://www.youtube.com/watch?v=vHWiDx_l4V0)
goes into more detail on this topic, and covers the implementation of
allocators.
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/03.filesystem-stat.zig | // hide-start
const std = @import("std");
const expect = std.testing.expect;
const eql = std.mem.eql;
// hide-end
test "file stat" {
const file = try std.fs.cwd().createFile(
"junk_file2.txt",
.{ .read = true },
);
defer file.close();
const stat = try file.stat();
try expect(stat.size == 0);
try expect(stat.kind == .file);
try expect(stat.ctime <= std.time.nanoTimestamp());
try expect(stat.mtime <= std.time.nanoTimestamp());
try expect(stat.atime <= std.time.nanoTimestamp());
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/02-arraylist.mdx | import CodeBlock from "@theme/CodeBlock";
import ArrayList from "!!raw-loader!./02.arraylist.zig";
# ArrayList
The
[`std.ArrayList`](https://ziglang.org/documentation/master/std/#std.ArrayList)
is commonly used throughout Zig, and serves as a buffer which can change in
size. `std.ArrayList(T)` is similar to C++'s `std::vector<T>` and Rust's
`Vec<T>`. The `deinit()` method frees all of the ArrayList's memory. The memory
can be read from and written to via its slice field - `.items`.
Here we will introduce the usage of the testing allocator. This is a special
allocator that only works in tests and can detect memory leaks. In your code,
use whatever allocator is appropriate.
<CodeBlock language="zig">{ArrayList}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/01.allocators-alloc.zig | const std = @import("std");
const expect = std.testing.expect;
test "allocation" {
const allocator = std.heap.page_allocator;
const memory = try allocator.alloc(u8, 100);
defer allocator.free(memory);
try expect(memory.len == 100);
try expect(@TypeOf(memory) == []u8);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/01.allocators-arena.zig | // hide-start
const std = @import("std");
const expect = std.testing.expect;
// hide-end
test "arena allocator" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
_ = try allocator.alloc(u8, 1);
_ = try allocator.alloc(u8, 10);
_ = try allocator.alloc(u8, 100);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/03.filesystem-cwd-create.zig | // hide-start
const std = @import("std");
const expect = std.testing.expect;
const eql = std.mem.eql;
// hide-end
test "createFile, write, seekTo, read" {
const file = try std.fs.cwd().createFile(
"junk_file.txt",
.{ .read = true },
);
defer file.close();
const bytes_written = try file.writeAll("Hello File!");
_ = bytes_written;
var buffer: [100]u8 = undefined;
try file.seekTo(0);
const bytes_read = try file.readAll(&buffer);
try expect(eql(u8, buffer[0..bytes_read], "Hello File!"));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/14-formatting-specifiers.md | # Formatting specifiers
[`std.fmt`](https://ziglang.org/documentation/master/std/#std;fmt) provides
options for formatting various data types.
`std.fmt.fmtSliceHexLower` and `std.fmt.fmtSliceHexUpper` provide hex formatting
for strings as well as `{x}` and `{X}` for ints.
```zig
const bufPrint = std.fmt.bufPrint;
test "hex" {
var b: [8]u8 = undefined;
_ = try bufPrint(&b, "{X}", .{4294967294});
try expect(eql(u8, &b, "FFFFFFFE"));
_ = try bufPrint(&b, "{x}", .{4294967294});
try expect(eql(u8, &b, "fffffffe"));
_ = try bufPrint(&b, "{}", .{std.fmt.fmtSliceHexLower("Zig!")});
try expect(eql(u8, &b, "5a696721"));
}
```
`{d}` performs decimal formatting for numeric types.
```zig
test "decimal float" {
var b: [4]u8 = undefined;
try expect(eql(
u8,
try bufPrint(&b, "{d}", .{16.5}),
"16.5",
));
}
```
`{c}` formats a byte into an ascii character.
```zig
test "ascii fmt" {
var b: [1]u8 = undefined;
_ = try bufPrint(&b, "{c}", .{66});
try expect(eql(u8, &b, "B"));
}
```
`std.fmt.fmtIntSizeDec` and `std.fmt.fmtIntSizeBin` output memory sizes in
metric (1000) and power-of-two (1024) based notation.
```zig
test "B Bi" {
var b: [32]u8 = undefined;
try expect(eql(u8, try bufPrint(&b, "{}", .{std.fmt.fmtIntSizeDec(1)}), "1B"));
try expect(eql(u8, try bufPrint(&b, "{}", .{std.fmt.fmtIntSizeBin(1)}), "1B"));
try expect(eql(u8, try bufPrint(&b, "{}", .{std.fmt.fmtIntSizeDec(1024)}), "1.024kB"));
try expect(eql(u8, try bufPrint(&b, "{}", .{std.fmt.fmtIntSizeBin(1024)}), "1KiB"));
try expect(eql(
u8,
try bufPrint(&b, "{}", .{std.fmt.fmtIntSizeDec(1024 * 1024 * 1024)}),
"1.073741824GB",
));
try expect(eql(
u8,
try bufPrint(&b, "{}", .{std.fmt.fmtIntSizeBin(1024 * 1024 * 1024)}),
"1GiB",
));
}
```
`{b}` and `{o}` output integers in binary and octal format.
```zig
test "binary, octal fmt" {
var b: [8]u8 = undefined;
try expect(eql(
u8,
try bufPrint(&b, "{b}", .{254}),
"11111110",
));
try expect(eql(
u8,
try bufPrint(&b, "{o}", .{254}),
"376",
));
}
```
`{*}` performs pointer formatting, printing the address rather than the value.
```zig
test "pointer fmt" {
var b: [16]u8 = undefined;
try expect(eql(
u8,
try bufPrint(&b, "{*}", .{@as(*u8, @ptrFromInt(0xDEADBEEF))}),
"u8@deadbeef",
));
}
```
`{e}` outputs floats in scientific notation.
```zig
test "scientific" {
var b: [16]u8 = undefined;
try expect(eql(
u8,
try bufPrint(&b, "{e}", .{3.14159}),
"3.14159e+00",
));
}
```
`{s}` outputs strings.
```zig
test "string fmt" {
var b: [6]u8 = undefined;
const hello: [*:0]const u8 = "hello!";
try expect(eql(
u8,
try bufPrint(&b, "{s}", .{hello}),
"hello!",
));
}
```
This list is non-exhaustive.
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/12-sorting.md | # Sorting
The standard library provides utilities for in-place sorting slices. Its basic
usage is as follows.
```zig
test "sorting" {
var data = [_]u8{ 10, 240, 0, 0, 10, 5 };
std.mem.sort(u8, &data, {}, comptime std.sort.asc(u8));
try expect(eql(u8, &data, &[_]u8{ 0, 0, 5, 10, 10, 240 }));
std.mem.sort(u8, &data, {}, comptime std.sort.desc(u8));
try expect(eql(u8, &data, &[_]u8{ 240, 10, 10, 5, 0, 0 }));
}
```
[`std.sort.asc`](https://ziglang.org/documentation/master/std/#std.sort.asc)
and [`.desc`](https://ziglang.org/documentation/master/std/#std.sort.desc)
create a comparison function for the given type at comptime; if non-numerical
types should be sorted, the user must provide their own comparison function.
[`std.mem.sort`](https://ziglang.org/documentation/master/std/#std.mem.sort)
has a best case of O(n), and an average and worst case of O(n*log(n)).
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/05-formatting.mdx | import CodeBlock from "@theme/CodeBlock";
import Fmt from "!!raw-loader!./05.formatting-fmt.zig";
import Print from "!!raw-loader!./05.formatting-print.zig";
import ArrayPrint from "!!raw-loader!./05.formatting-array-print.zig";
import Custom from "!!raw-loader!./05.formatting-custom.zig";
# Formatting
[`std.fmt`](https://ziglang.org/documentation/master/std/#std.fmt) provides
ways to format data to and from strings.
A basic example of creating a formatted string. The format string must be
compile time known. The `d` here denotes that we want a decimal number.
<CodeBlock language="zig">{Fmt}</CodeBlock>
Writers conveniently have a `print` method, which works similarly.
<CodeBlock language="zig">{Print}</CodeBlock>
Take a moment to appreciate that you now know from top to bottom how printing
Hello World works.
[`std.debug.print`](https://ziglang.org/documentation/master/std/#std.debug.print)
works the same, except it writes to stderr and is protected by a mutex.
{/* Code snippet not tested as it uses stdin/stdout */}
```zig
// hide-start
const std = @import("std");
const expect = std.testing.expect;
const eql = std.mem.eql;
// hide-end
test "hello world" {
const out_file = std.io.getStdOut();
try out_file.writer().print(
"Hello, {s}!\n",
.{"World"},
);
}
```
We have used the `{s}` format specifier up until this point to print strings.
Here, we will use `{any}`, which gives us the default formatting.
<CodeBlock language="zig">{ArrayPrint}</CodeBlock>
Let's create a type with custom formatting by giving it a `format` function.
This function must be marked as `pub` so that std.fmt can access it (more on
packages later). You may notice the usage of `{s}` instead of `{}` - this is the
format specifier for strings (more on format specifiers later). This is used
here as `{}` defaults to array printing over string printing.
<CodeBlock language="zig">{Custom}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/07-random-numbers.md | # Random Numbers
Here ,we create a new prng using a 64 bit random seed. a, b, c, and d are given
random values via this prng. The expressions giving c and d values are
equivalent. `DefaultPrng` is `Xoroshiro128`; there are other prngs available in
std.rand.
```zig
test "random numbers" {
var prng = std.rand.DefaultPrng.init(blk: {
var seed: u64 = undefined;
try std.os.getrandom(std.mem.asBytes(&seed));
break :blk seed;
});
const rand = prng.random();
const a = rand.float(f32);
const b = rand.boolean();
const c = rand.int(u8);
const d = rand.intRangeAtMost(u8, 0, 255);
//suppress unused constant compile error
_ = .{ a, b, c, d };
}
```
Cryptographically secure random is also available.
```zig
test "crypto random numbers" {
const rand = std.crypto.random;
const a = rand.float(f32);
const b = rand.boolean();
const c = rand.int(u8);
const d = rand.intRangeAtMost(u8, 0, 255);
//suppress unused constant compile error
_ = .{ a, b, c, d };
}
```
:::info
We can now use our knowledge of std.rand and [make a guessing game together](/posts/a-guessing-game).
:::
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/01.allocators-fba.zig | // hide-start
const std = @import("std");
const expect = std.testing.expect;
// hide-end
test "fixed buffer allocator" {
var buffer: [1000]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buffer);
const allocator = fba.allocator();
const memory = try allocator.alloc(u8, 100);
defer allocator.free(memory);
try expect(memory.len == 100);
try expect(@TypeOf(memory) == []u8);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/05.formatting-custom.zig | // hide-start
const std = @import("std");
const expect = std.testing.expect;
const eql = std.mem.eql;
const test_allocator = std.testing.allocator;
// hide-end
const Person = struct {
name: []const u8,
birth_year: i32,
death_year: ?i32,
pub fn format(
self: Person,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
_ = options;
try writer.print("{s} ({}-", .{
self.name, self.birth_year,
});
if (self.death_year) |year| {
try writer.print("{}", .{year});
}
try writer.writeAll(")");
}
};
test "custom fmt" {
const john = Person{
.name = "John Carmack",
.birth_year = 1970,
.death_year = null,
};
const john_string = try std.fmt.allocPrint(
test_allocator,
"{s}",
.{john},
);
defer test_allocator.free(john_string);
try expect(eql(
u8,
john_string,
"John Carmack (1970-)",
));
const claude = Person{
.name = "Claude Shannon",
.birth_year = 1916,
.death_year = 2001,
};
const claude_string = try std.fmt.allocPrint(
test_allocator,
"{s}",
.{claude},
);
defer test_allocator.free(claude_string);
try expect(eql(
u8,
claude_string,
"Claude Shannon (1916-2001)",
));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/06-json.md | # JSON
Let's parse a JSON string into a struct type, using the streaming parser.
```zig
const Place = struct { lat: f32, long: f32 };
test "json parse" {
const parsed = try std.json.parseFromSlice(
Place,
test_allocator,
\\{ "lat": 40.684540, "long": -74.401422 }
,
.{},
);
defer parsed.deinit();
const place = parsed.value;
try expect(place.lat == 40.684540);
try expect(place.long == -74.401422);
}
```
And using stringify to turn arbitrary data into a string.
```zig
test "json stringify" {
const x = Place{
.lat = 51.997664,
.long = -0.740687,
};
var buf: [100]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buf);
var string = std.ArrayList(u8).init(fba.allocator());
try std.json.stringify(x, .{}, string.writer());
try expect(eql(u8, string.items,
\\{"lat":5.199766540527344e+01,"long":-7.406870126724243e-01}
));
}
```
The JSON parser requires an allocator for javascript's string, array, and map
types.
```zig
test "json parse with strings" {
const User = struct { name: []u8, age: u16 };
const parsed = try std.json.parseFromSlice(User, test_allocator,
\\{ "name": "Joe", "age": 25 }
, .{},);
defer parsed.deinit();
const user = parsed.value;
try expect(eql(u8, user.name, "Joe"));
try expect(user.age == 25);
}
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/13-iterators.md | # Iterators
It is a common idiom to have a struct type with a `next` function with an
optional in its return type, so that the function may return a null to indicate
that iteration is finished.
[`std.mem.SplitIterator`](https://ziglang.org/documentation/master/std/#std.mem.SplitIterator)
(and the subtly different
[`std.mem.TokenIterator`](https://ziglang.org/documentation/master/std/#std.mem.TokenIterator))
is an example of this pattern.
```zig
test "split iterator" {
const text = "robust, optimal, reusable, maintainable, ";
var iter = std.mem.split(u8, text, ", ");
try expect(eql(u8, iter.next().?, "robust"));
try expect(eql(u8, iter.next().?, "optimal"));
try expect(eql(u8, iter.next().?, "reusable"));
try expect(eql(u8, iter.next().?, "maintainable"));
try expect(eql(u8, iter.next().?, ""));
try expect(iter.next() == null);
}
```
Some iterators have a `!?T` return type, as opposed to ?T. `!?T` requires that
we unpack the error union before the optional, meaning that the work done to get
to the next iteration may error. Here is an example of doing this with a loop.
[`cwd`](https://ziglang.org/documentation/master/std/#std;fs.cwd) has to be
opened with iterate permissions in order for the directory iterator to work.
```zig
test "iterator looping" {
var iter = (try std.fs.cwd().openIterableDir(
".",
.{},
)).iterate();
var file_count: usize = 0;
while (try iter.next()) |entry| {
if (entry.kind == .file) file_count += 1;
}
try expect(file_count > 0);
}
```
Here we will implement a custom iterator. This will iterate over a slice of
strings, yielding the strings which contain a given string.
```zig
const ContainsIterator = struct {
strings: []const []const u8,
needle: []const u8,
index: usize = 0,
fn next(self: *ContainsIterator) ?[]const u8 {
const index = self.index;
for (self.strings[index..]) |string| {
self.index += 1;
if (std.mem.indexOf(u8, string, self.needle)) |_| {
return string;
}
}
return null;
}
};
test "custom iterator" {
var iter = ContainsIterator{
.strings = &[_][]const u8{ "one", "two", "three" },
.needle = "e",
};
try expect(eql(u8, iter.next().?, "one"));
try expect(eql(u8, iter.next().?, "three"));
try expect(iter.next() == null);
}
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/04-readers-and-writers.mdx | import CodeBlock from "@theme/CodeBlock";
import Writer from "!!raw-loader!./04.readers-and-writers-writer.zig";
import Reader from "!!raw-loader!./04.readers-and-writers-reader.zig";
import Custom from "!!raw-loader!./04.readers-and-writers-custom.zig";
# Readers and Writers
[`std.io.Writer`](https://ziglang.org/documentation/master/std/#std.io.Writer)
and
[`std.io.Reader`](https://ziglang.org/documentation/master/std/#std.io.Reader)
provide standard ways of making use of IO. `std.ArrayList(u8)` has a `writer`
method which gives us a writer. Let's use it.
<CodeBlock language="zig">{Writer}</CodeBlock>
Here we will use a reader to copy the file's contents into an allocated buffer.
The second argument of
[`readAllAlloc`](https://ziglang.org/documentation/master/std/#std.io.Reader.readAllAlloc)
is the maximum size that it may allocate; if the file is larger than this, it
will return `error.StreamTooLong`.
<CodeBlock language="zig">{Reader}</CodeBlock>
A common usecase for readers is to read until the next line (e.g. for user
input). Here we will do this with the
[`std.io.getStdIn()`](https://ziglang.org/documentation/master/std/#std.io.getStdIn)
file.
{/* Code snippet not tested as it uses stdin/stdout */}
```zig
// hide-start
const std = @import("std");
const expect = std.testing.expect;
const eql = std.mem.eql;
// hide-end
fn nextLine(reader: anytype, buffer: []u8) !?[]const u8 {
var line = (try reader.readUntilDelimiterOrEof(
buffer,
'\n',
)) orelse return null;
// trim annoying windows-only carriage return character
if (@import("builtin").os.tag == .windows) {
return std.mem.trimRight(u8, line, "\r");
} else {
return line;
}
}
test "read until next line" {
const stdout = std.io.getStdOut();
const stdin = std.io.getStdIn();
try stdout.writeAll(
\\ Enter your name:
);
var buffer: [100]u8 = undefined;
const input = (try nextLine(stdin.reader(), &buffer)).?;
try stdout.writer().print(
"Your name is: \"{s}\"\n",
.{input},
);
}
```
An
[`std.io.Writer`](https://ziglang.org/documentation/master/std/#std.io.Writer)
type consists of a context type, error set, and a write function. The write
function must take in the context type and a byte slice. The write function must
also return an error union of the Writer type's error set and the number of
bytes written. Let's create a type that implements a writer.
<CodeBlock language="zig">{Custom}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/01.allocators-create.zig | // hide-start
const std = @import("std");
const expect = std.testing.expect;
// hide-end
test "allocator create/destroy" {
const byte = try std.heap.page_allocator.create(u8);
defer std.heap.page_allocator.destroy(byte);
byte.* = 128;
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/15-advanced-formatting.md | ---
pagination_next: build-system/build-modes
---
# Advanced Formatting
So far we have only covered formatting specifiers. Format strings actually
follow this format, where between each pair of square brackets is a parameter
you have to replace with something.
`{[position][specifier]:[fill][alignment][width].[precision]}`
| Name | Meaning |
| --------- | -------------------------------------------------------------------------------- |
| Position | The index of the argument that should be inserted |
| Specifier | A type-dependent formatting option |
| Fill | A single character used for padding |
| Alignment | One of three characters < ^ or >; these are for left, middle and right alignment |
| Width | The total width of the field (characters) |
| Precision | How many decimals a formatted number should have |
Position usage.
```zig
test "position" {
var b: [3]u8 = undefined;
try expect(eql(
u8,
try bufPrint(&b, "{0s}{0s}{1s}", .{ "a", "b" }),
"aab",
));
}
```
Fill, alignment and width being used.
```zig
test "fill, alignment, width" {
var b: [6]u8 = undefined;
try expect(eql(
u8,
try bufPrint(&b, "{s: <5}", .{"hi!"}),
"hi! ",
));
try expect(eql(
u8,
try bufPrint(&b, "{s:_^6}", .{"hi!"}),
"_hi!__",
));
try expect(eql(
u8,
try bufPrint(&b, "{s:!>4}", .{"hi!"}),
"!hi!",
));
}
```
Using a specifier with precision.
```zig
test "precision" {
var b: [4]u8 = undefined;
try expect(eql(
u8,
try bufPrint(&b, "{d:.2}", .{3.14159}),
"3.14",
));
}
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/05.formatting-fmt.zig | // hide-start
const std = @import("std");
const expect = std.testing.expect;
const eql = std.mem.eql;
// hide-end
const test_allocator = std.testing.allocator;
test "fmt" {
const string = try std.fmt.allocPrint(
test_allocator,
"{d} + {d} = {d}",
.{ 9, 10, 19 },
);
defer test_allocator.free(string);
try expect(eql(u8, string, "9 + 10 = 19"));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/09-threads.md | # Threads
While Zig provides more advanced ways of writing concurrent and parallel code,
[`std.Thread`](https://ziglang.org/documentation/master/std/#std.Thread) is
available for making use of OS threads. Let's make use of an OS thread.
```zig
fn ticker(step: u8) void {
while (true) {
std.time.sleep(1 * std.time.ns_per_s);
tick += @as(isize, step);
}
}
var tick: isize = 0;
test "threading" {
var thread = try std.Thread.spawn(.{}, ticker, .{@as(u8, 1)});
_ = thread;
try expect(tick == 0);
std.time.sleep(3 * std.time.ns_per_s / 2);
try expect(tick == 1);
}
```
Threads, however, aren't particularly useful without strategies for thread
safety.
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/02.arraylist.zig | // hide-start
const std = @import("std");
const expect = std.testing.expect;
// hide-end
const eql = std.mem.eql;
const ArrayList = std.ArrayList;
const test_allocator = std.testing.allocator;
test "arraylist" {
var list = ArrayList(u8).init(test_allocator);
defer list.deinit();
try list.append('H');
try list.append('e');
try list.append('l');
try list.append('l');
try list.append('o');
try list.appendSlice(" World!");
try expect(eql(u8, list.items, "Hello World!"));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/01.allocators-gpa.zig | // hide-start
const std = @import("std");
const expect = std.testing.expect;
// hide-end
test "GPA" {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
defer {
const deinit_status = gpa.deinit();
//fail test; can't try in defer as defer is executed after we return
if (deinit_status == .leak) expect(false) catch @panic("TEST FAIL");
}
const bytes = try allocator.alloc(u8, 100);
defer allocator.free(bytes);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/03.filesystem-make-dir-iterable.zig | // hide-start
const std = @import("std");
const expect = std.testing.expect;
const eql = std.mem.eql;
// hide-end
test "make dir" {
try std.fs.cwd().makeDir("test-tmp");
var iter_dir = try std.fs.cwd().openIterableDir(
"test-tmp",
.{},
);
defer {
iter_dir.close();
std.fs.cwd().deleteTree("test-tmp") catch unreachable;
}
_ = try iter_dir.dir.createFile("x", .{});
_ = try iter_dir.dir.createFile("y", .{});
_ = try iter_dir.dir.createFile("z", .{});
var file_count: usize = 0;
var iter = iter_dir.iterate();
while (try iter.next()) |entry| {
if (entry.kind == .file) file_count += 1;
}
try expect(file_count == 3);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/02-standard-library/04.readers-and-writers-writer.zig | // hide-start
const std = @import("std");
const expect = std.testing.expect;
const eql = std.mem.eql;
// hide-end
const ArrayList = std.ArrayList;
const test_allocator = std.testing.allocator;
test "io writer usage" {
var list = ArrayList(u8).init(test_allocator);
defer list.deinit();
const bytes_written = try list.writer().write(
"Hello World!",
);
try expect(bytes_written == 12);
try expect(eql(u8, list.items, "Hello World!"));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/19.floats-conversion.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "int-float conversion" {
const a: i32 = 0;
const b = @as(f32, @floatFromInt(a));
const c = @as(i32, @intFromFloat(b));
try expect(c == a);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/14.slices.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
fn total(values: []const u8) usize {
var sum: usize = 0;
for (values) |v| sum += v;
return sum;
}
test "slices" {
const array = [_]u8{ 1, 2, 3, 4, 5 };
const slice = array[0..3];
try expect(total(slice) == 6);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/18.integer-casting.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "@intCast" {
const x: u64 = 200;
const y = @as(u8, @intCast(x));
try expect(@TypeOf(y) == u8);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/08.error-set.zig | const FileOpenError = error{
AccessDenied,
OutOfMemory,
FileNotFound,
};
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/18-integer-rules.mdx | import CodeBlock from "@theme/CodeBlock";
import IntegerWidening from "!!raw-loader!./18.integer-widening.zig";
import IntegerCasting from "!!raw-loader!./18.integer-casting.zig";
import IntegerSafeOverflow from "!!raw-loader!./18.integer-safe-overflow.zig";
# Integer Rules
Zig supports hex, octal and binary integer literals.
```zig
const decimal_int: i32 = 98222;
const hex_int: u8 = 0xff;
const another_hex_int: u8 = 0xFF;
const octal_int: u16 = 0o755;
const binary_int: u8 = 0b11110000;
```
Underscores may also be placed between digits as a visual separator.
```zig
const one_billion: u64 = 1_000_000_000;
const binary_mask: u64 = 0b1_1111_1111;
const permissions: u64 = 0o7_5_5;
const big_address: u64 = 0xFF80_0000_0000_0000;
```
"Integer Widening" is allowed, which means that integers of a type may coerce to
an integer of another type, providing that the new type can fit all of the
values that the old type can.
<CodeBlock language="zig">{IntegerWidening}</CodeBlock>
If you have a value stored in an integer that cannot coerce to the type that you
want, [`@intCast`](https://ziglang.org/documentation/master/#intCast) may be
used to explicitly convert from one type to the other. If the value given is out
of the range of the destination type, this is detectable illegal behaviour.
<CodeBlock language="zig">{IntegerCasting}</CodeBlock>
Integers, by default, are not allowed to overflow. Overflows are detectable
illegal behaviour. Sometimes, being able to overflow integers in a well-defined
manner is a wanted behaviour. For this use case, Zig provides overflow
operators.
| Normal Operator | Wrapping Operator |
| --------------- | ----------------- |
| + | +% |
| - | -% |
| \* | \*% |
| += | +%= |
| -= | -%= |
| \*= | \*%= |
<CodeBlock language="zig">{IntegerSafeOverflow}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/07.defer.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
test "defer" {
var x: i16 = 5;
{
defer x += 2;
try expect(x == 5);
}
try expect(x == 7);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/27-opaque.md | # Opaque
[`opaque`](https://ziglang.org/documentation/master/#opaque) types in Zig have
an unknown (albeit non-zero) size and alignment. Because of this these data
types cannot be stored directly. These are used to maintain type safety with
pointers to types that we don't have information about.
<!--fail_test-->
```zig
const Window = opaque {};
const Button = opaque {};
extern fn show_window(*Window) callconv(.C) void;
test "opaque" {
var main_window: *Window = undefined;
show_window(main_window);
var ok_button: *Button = undefined;
show_window(ok_button);
}
```
```
./test-c1.zig:653:17: error: expected type '*Window', found '*Button'
show_window(ok_button);
^
./test-c1.zig:653:17: note: pointer type child 'Button' cannot cast into pointer type child 'Window'
show_window(ok_button);
^
```
Opaque types may have declarations in their definitions (the same as structs,
enums and unions).
<!--no_test-->
```zig
const Window = opaque {
fn show(self: *Window) void {
show_window(self);
}
};
extern fn show_window(*Window) callconv(.C) void;
test "opaque with declarations" {
var main_window: *Window = undefined;
main_window.show();
}
```
The typical usecase of opaque is to maintain type safety when interoperating
with C code that does not expose complete type information.
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/29-sentinel-termination.md | # Sentinel Termination
Arrays, slices and many pointers may be terminated by a value of their child
type. This is known as sentinel termination. These follow the syntax `[N:t]T`,
`[:t]T`, and `[*:t]T`, where `t` is a value of the child type `T`.
An example of a sentinel terminated array. The built-in
[`@ptrCast`](https://ziglang.org/documentation/master/#ptrCast) is used to
perform an unsafe type conversion. This shows us that the last element of the
array is followed by a 0 byte.
```zig
test "sentinel termination" {
const terminated = [3:0]u8{ 3, 2, 1 };
try expect(terminated.len == 3);
try expect(@as(*const [4]u8, @ptrCast(&terminated))[3] == 0);
}
```
The types of string literals is `*const [N:0]u8`, where N is the length of the
string. This allows string literals to coerce to sentinel terminated slices, and
sentinel terminated many pointers. Note: string literals are UTF-8 encoded.
```zig
test "string literal" {
try expect(@TypeOf("hello") == *const [5:0]u8);
}
```
`[*:0]u8` and `[*:0]const u8` perfectly model C's strings.
```zig
test "C string" {
const c_string: [*:0]const u8 = "hello";
var array: [5]u8 = undefined;
var i: usize = 0;
while (c_string[i] != 0) : (i += 1) {
array[i] = c_string[i];
}
}
```
Sentinel terminated types coerce to their non-sentinel-terminated counterparts.
```zig
test "coercion" {
var a: [*:0]u8 = undefined;
const b: [*]u8 = a;
_ = b;
var c: [5:0]u8 = undefined;
const d: [5]u8 = c;
_ = d;
var e: [:0]f32 = undefined;
const f: []f32 = e;
_ = f;
}
```
Sentinel terminated slicing is provided which can be used to create a sentinel
terminated slice with the syntax `x[n..m:t]`, where `t` is the terminator value.
Doing this is an assertion from the programmer that the memory is terminated
where it should be - getting this wrong is detectable illegal behaviour.
```zig
test "sentinel terminated slicing" {
var x = [_:0]u8{255} ** 3;
const y = x[0..3 :0];
_ = y;
}
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/_category_.json | {
"label": "Language",
"link": {
"description": "Getting started with the Zig programming language."
}
} |
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/21-labelled-loops.md | # Labelled Loops
Loops can be given labels, allowing you to `break` and `continue` to outer
loops.
```zig
test "nested continue" {
var count: usize = 0;
outer: for ([_]i32{ 1, 2, 3, 4, 5, 6, 7, 8 }) |_| {
for ([_]i32{ 1, 2, 3, 4, 5 }) |_| {
count += 1;
continue :outer;
}
}
try expect(count == 8);
}
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/08.error-set-inferred.zig | fn createFile() !void {
return error.AccessDenied;
}
test "inferred error set" {
//type coercion successfully takes place
const x: error{AccessDenied}!void = createFile();
//Zig does not let us ignore error unions via _ = x;
//we must unwrap it with "try", "catch", or "if" by any means
_ = x catch {};
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/14-slices.mdx | import CodeBlock from "@theme/CodeBlock";
import Slices from "!!raw-loader!./14.slices.zig";
import Slices2 from "!!raw-loader!./14.slices-2.zig";
# Slices
Slices can be thought of as a pair of `[*]T` (the pointer to the data) and a
`usize` (the element count). Their syntax is `[]T`, with `T` being the child
type. Slices are used heavily throughout Zig for when you need to operate on
arbitrary amounts of data. Slices have the same attributes as pointers, meaning
that there also exists const slices. For loops also operate over slices. String
literals in Zig coerce to `[]const u8`.
Here, the syntax `x[n..m]` is used to create a slice from an array. This is
called **slicing**, and creates a slice of the elements starting at `x[n]` and
ending at `x[m - 1]`. This example uses a const slice, as the values to which
the slice points need not be modified.
<CodeBlock language="zig">{Slices}</CodeBlock>
When these `n` and `m` values are both known at compile time, slicing will
actually produce a pointer to an array. This is not an issue as a pointer to an
array i.e. `*[N]T` will coerce to a `[]T`.
<CodeBlock language="zig">{Slices2}</CodeBlock>
The syntax `x[n..]` can also be used when you want to slice to the end.
```zig
test "slices 3" {
var array = [_]u8{ 1, 2, 3, 4, 5 };
var slice = array[0..];
_ = slice;
}
```
Types that may be sliced are arrays, many pointers and slices.
:::info
We can now apply our knowledge and [make another program together](/posts/fahrenheit-to-celsius).
:::
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/16.struct.zig | const Vec3 = struct { x: f32, y: f32, z: f32 };
test "struct usage" {
const my_vector = Vec3{
.x = 0,
.y = 100,
.z = 50,
};
_ = my_vector;
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/31-imports.md | ---
pagination_next: standard-library/allocators
---
# Imports
The built-in function
[`@import`](https://ziglang.org/documentation/master/#import) takes in a file,
and gives you a struct type based on that file. All declarations labelled as
`pub` (for public) will end up in this struct type, ready for use.
`@import("std")` is a special case in the compiler, and gives you access to the
standard library. Other
[`@import`](https://ziglang.org/documentation/master/#import)s will take in a
file path, or a package name (more on packages in a later chapter).
We will explore more of the standard library in later chapters.
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/16.struct-defaults.zig | const Vec4 = struct { x: f32 = 0, y: f32 = 0, z: f32 = 0, w: f32 = 0 };
test "struct defaults" {
const my_vector = Vec4{
.x = 25,
.y = -50,
};
_ = my_vector;
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/19-floats.mdx | import CodeBlock from "@theme/CodeBlock";
import FloatsWidening from "!!raw-loader!./19.floats-widening.zig";
import FloatsLiterals from "!!raw-loader!./19.floats-literals.zig";
import FloatsHexUnderscores from "!!raw-loader!./19.floats-hex-underscores.zig";
import FloatsConversion from "!!raw-loader!./19.floats-conversion.zig";
# Floats
Zig's floats are strictly IEEE compliant unless
[`@setFloatMode(.Optimized)`](https://ziglang.org/documentation/master/#setFloatMode)
is used, which is equivalent to GCC's `-ffast-math`. Floats coerce to larger
float types.
<CodeBlock language="zig">{FloatsWidening}</CodeBlock>
Floats support multiple kinds of literal.
<CodeBlock language="zig">{FloatsLiterals}</CodeBlock>
Underscores may also be placed between digits.
<CodeBlock language="zig">{FloatsHexUnderscores}</CodeBlock>
Integers and floats may be converted using the built-in functions
[`@floatFromInt`](https://ziglang.org/documentation/0.11.0/#floatFromInt) and
[`@intFromFloat`](https://ziglang.org/documentation/0.11.0/#intFromFloat).
[`@floatFromInt`](https://ziglang.org/documentation/0.11.0/#floatFromInt) is
always safe, whereas
[`@intFromFloat`](https://ziglang.org/documentation/0.11.0/#intFromFloat) is
detectable illegal behaviour if the float value cannot fit in the integer
destination type.
<CodeBlock language="zig">{FloatsConversion}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/08.error-set-merge.zig | const A = error{ NotDir, PathNotFound };
const B = error{ OutOfMemory, PathNotFound };
const C = A || B;
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/18.integer-widening.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "integer widening" {
const a: u8 = 250;
const b: u16 = a;
const c: u32 = b;
try expect(c == a);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/16-structs.mdx | import CodeBlock from "@theme/CodeBlock";
import Struct from "!!raw-loader!./16.struct.zig";
import StructDefaults from "!!raw-loader!./16.struct-defaults.zig";
import StructDeclarations from "!!raw-loader!./16.struct-declarations.zig";
# Structs
Structs are Zig's most common kind of composite data type, allowing you to
define types that can store a fixed set of named fields. Zig gives no guarantees
about the in-memory order of fields in a struct or its size. Like arrays,
structs are also neatly constructed with `T{}` syntax. Here is an example of
declaring and filling a struct.
<CodeBlock language="zig">{Struct}</CodeBlock>
Struct fields cannot be implicitly uninitialised:
```zig
test "missing struct field" {
const my_vector = Vec3{
.x = 0,
.z = 50,
};
_ = my_vector;
}
```
```
error: missing field: 'y'
const my_vector = Vec3{
^
```
Fields may be given defaults:
<CodeBlock language="zig">{StructDefaults}</CodeBlock>
Like enums, structs may also contain functions and declarations.
Structs have the unique property that when given a pointer to a struct, one
level of dereferencing is done automatically when accessing fields. Notice how,
in this example, self.x and self.y are accessed in the swap function without
needing to dereference the self pointer.
<CodeBlock language="zig">{StructDeclarations}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/19.floats-hex-underscores.zig | const lightspeed: f64 = 299_792_458.000_000;
const nanosecond: f64 = 0.000_000_001;
const more_hex: f64 = 0x1234_5678.9ABC_CDEFp-10;
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/03.if-expression.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
test "if statement expression" {
const a = true;
var x: u16 = 0;
x += if (a) 1 else 2;
try expect(x == 1);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/05.for.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
test "for" {
//character literals are equivalent to integer literals
const string = [_]u8{ 'a', 'b', 'c' };
for (string, 0..) |character, index| {
_ = character;
_ = index;
}
for (string) |character| {
_ = character;
}
for (string, 0..) |_, index| {
_ = index;
}
for (string) |_| {}
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/08-errors.mdx | import CodeBlock from "@theme/CodeBlock";
import ErrorSet from "!!raw-loader!./08.error-set.zig";
import ErrorSetCoercion from "!!raw-loader!./08.error-set-coercion.zig";
import ErrorUnion from "!!raw-loader!./08.error-union.zig";
import ErrorPayloadCapture from "!!raw-loader!./08.error-payload-capture.zig";
import ErrorTry from "!!raw-loader!./08.error-try.zig";
import Errdefer from "!!raw-loader!./08.errdefer.zig";
import ErrorSetInferred from "!!raw-loader!./08.error-set-inferred.zig";
import ErrorSetMerge from "!!raw-loader!./08.error-set-merge.zig";
# Errors
An error set is like an enum (details on Zig's enums later), where each error in
the set is a value. There are no exceptions in Zig; errors are values. Let's
create an error set.
<CodeBlock language="zig">{ErrorSet}</CodeBlock>
Error sets coerce to their supersets.
<CodeBlock language="zig">{ErrorSetCoercion}</CodeBlock>
An error set type and another type can be combined with the `!` operator to form
an error union type. Values of these types may be an error value or a value of
the other type.
Let's create a value of an error union type. Here
[`catch`](https://ziglang.org/documentation/master/#catch) is used, which is
followed by an expression which is evaluated when the value preceding it is an
error. The catch here is used to provide a fallback value, but could instead be
a [`noreturn`](https://ziglang.org/documentation/master/#noreturn) - the type of
`return`, `while (true)` and others.
<CodeBlock language="zig">{ErrorUnion}</CodeBlock>
Functions often return error unions. Here's one using a catch, where the `|err|`
syntax receives the value of the error. This is called **payload capturing**,
and is used similarly in many places. We'll talk about it in more detail later
in the chapter. Side note: some languages use similar syntax for lambdas - this
is not true for Zig.
<CodeBlock language="zig">{ErrorPayloadCapture}</CodeBlock>
`try x` is a shortcut for `x catch |err| return err`, and is commonly used where
handling an error isn't appropriate. Zig's
[`try`](https://ziglang.org/documentation/master/#try) and
[`catch`](https://ziglang.org/documentation/master/#catch) are unrelated to
try-catch in other languages.
<CodeBlock language="zig">{ErrorTry}</CodeBlock>
[`errdefer`](https://ziglang.org/documentation/master/#errdefer) works like
[`defer`](https://ziglang.org/documentation/master/#defer), but only executing
when the function is returned from with an error inside of the
[`errdefer`](https://ziglang.org/documentation/master/#errdefer)'s block.
<CodeBlock language="zig">{Errdefer}</CodeBlock>
Error unions returned from a function can have their error sets inferred by not
having an explicit error set. This inferred error set contains all possible
errors that the function may return.
<CodeBlock language="zig">{ErrorSetInferred}</CodeBlock>
Error sets can be merged.
<CodeBlock language="zig">{ErrorSetMerge}</CodeBlock>
`anyerror` is the global error set, which due to being the superset of all error
sets, can have an error from any set coerced to it. Its usage should be
generally avoided.
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/15.enum-methods.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
const Suit = enum {
clubs,
spades,
diamonds,
hearts,
pub fn isClubs(self: Suit) bool {
return self == Suit.clubs;
}
};
test "enum method" {
try expect(Suit.spades.isClubs() == Suit.isClubs(.spades));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/09.switch-statement.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
test "switch statement" {
var x: i8 = 10;
switch (x) {
-1...1 => {
x = -x;
},
10, 100 => {
//special considerations must be made
//when dividing signed integers
x = @divExact(x, 10);
},
else => {},
}
try expect(x == 1);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/04.while-continue-expression.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
test "while with continue expression" {
var sum: u8 = 0;
var i: u8 = 1;
while (i <= 10) : (i += 1) {
sum += i;
}
try expect(sum == 55);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/05-for-loops.mdx | import CodeBlock from "@theme/CodeBlock";
import For from "!!raw-loader!./05.for.zig";
# For loops
For loops are used to iterate over arrays (and other types, to be discussed
later). For loops follow this syntax. Like while, for loops can use `break` and
`continue`. Here, we've had to assign values to `_`, as Zig does not allow us to
have unused values.
<CodeBlock language="zig">{For}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/03.expect.zig | const expect = @import("std").testing.expect;
test "if statement" {
const a = true;
var x: u16 = 0;
if (a) {
x += 1;
} else {
x += 2;
}
try expect(x == 1);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/11.pointers.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
fn increment(num: *u8) void {
num.* += 1;
}
test "pointers" {
var x: u8 = 1;
increment(&x);
try expect(x == 2);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/15.enum-declarations.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
const Mode = enum {
var count: u32 = 0;
on,
off,
};
test "hmm" {
Mode.count += 1;
try expect(Mode.count == 1);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/03-if.mdx | import CodeBlock from "@theme/CodeBlock";
import Expect from "!!raw-loader!./03.expect.zig";
import IfExpression from "!!raw-loader!./03.if-expression.zig";
# If Expressions
Zig's if statements accept `bool` values (i.e. `true` or `false`). Unlike languages
like C or Javascript, there are no values that implicitly coerce to bool values.
Here, we will introduce testing. Save the below code and compile + run it with
`zig test file-name.zig`. We will be using the
[`expect`](https://ziglang.org/documentation/master/std/#std;testing.expect)
function from the standard library, which will cause the test to fail if it's
given the value `false`. When a test fails, the error and stack trace will be
shown.
<CodeBlock language="zig">{Expect}</CodeBlock>
If statements also work as expressions.
<CodeBlock language="zig">{IfExpression}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/04.while-continue.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
test "while with continue" {
var sum: u8 = 0;
var i: u8 = 0;
while (i <= 3) : (i += 1) {
if (i == 2) continue;
sum += i;
}
try expect(sum == 4);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/06.functions.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
fn addFive(x: u32) u32 {
return x + 5;
}
test "function" {
const y = addFive(0);
try expect(@TypeOf(y) == u32);
try expect(y == 5);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/07-defer.mdx | import CodeBlock from "@theme/CodeBlock";
import Defer from "!!raw-loader!./07.defer.zig";
import DeferMulti from "!!raw-loader!./07.defer-multi.zig";
# Defer
Defer is used to execute a statement while exiting the current block.
<CodeBlock language="zig">{Defer}</CodeBlock>
When there are multiple defers in a single block, they are executed in reverse
order.
<CodeBlock language="zig">{DeferMulti}</CodeBlock>
Defer is useful to ensure that resources are cleaned up when they are no longer needed.
Instead of needing to remember to manually free up the resource,
you can add a defer statement right next to the statement which allocates that resource.
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/16.struct-declarations.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
const Stuff = struct {
x: i32,
y: i32,
fn swap(self: *Stuff) void {
const tmp = self.x;
self.x = self.y;
self.y = tmp;
}
};
test "automatic dereference" {
var thing = Stuff{ .x = 10, .y = 20 };
thing.swap();
try expect(thing.x == 20);
try expect(thing.y == 10);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/18.integer-safe-overflow.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "well defined overflow" {
var a: u8 = 255;
a +%= 1;
try expect(a == 0);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/08.error-payload-capture.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
fn failingFunction() error{Oops}!void {
return error.Oops;
}
test "returning an error" {
failingFunction() catch |err| {
try expect(err == error.Oops);
return;
};
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/30-vectors.md | # Vectors
Zig provides vector types for SIMD. These are not to be conflated with vectors
in a mathematical sense, or vectors like C++'s std::vector (for this, see
"Arraylist" in chapter 2). Vectors may be created using the
[`@Type`](https://ziglang.org/documentation/master/#Type) built-in we used
earlier, and
[`std.meta.Vector`](https://ziglang.org/documentation/master/std/#std;meta.Vector)
provides a shorthand for this.
Vectors can only have child types of booleans, integers, floats and pointers.
Operations between vectors with the same child type and length can take place.
These operations are performed on each of the values in the
vector.[`std.meta.eql`](https://ziglang.org/documentation/master/std/#std;meta.eql)
is used here to check for equality between two vectors (also useful for other
types like structs).
```zig
const meta = @import("std").meta;
test "vector add" {
const x: @Vector(4, f32) = .{ 1, -10, 20, -1 };
const y: @Vector(4, f32) = .{ 2, 10, 0, 1 };
const z = x + y;
try expect(meta.eql(z, @Vector(4, f32){ 3, 0, 20, 0 }));
}
```
Vectors are indexable.
```zig
test "vector indexing" {
const x: @Vector(4, u8) = .{ 255, 0, 255, 0 };
try expect(x[0] == 255);
}
```
The built-in function
[`@splat`](https://ziglang.org/documentation/master/#splat) may be used to
construct a vector where all of the values are the same. Here we use it to
multiply a vector by a scalar.
```zig
test "vector * scalar" {
const x: @Vector(3, f32) = .{ 12.5, 37.5, 2.5 };
const y = x * @as(@Vector(3, f32), @splat(2));
try expect(meta.eql(y, @Vector(3, f32){ 25, 75, 5 }));
}
```
Vectors do not have a `len` field like arrays, but may still be looped over.
```zig
test "vector looping" {
const x = @Vector(4, u8){ 255, 0, 255, 0 };
var sum = blk: {
var tmp: u10 = 0;
var i: u8 = 0;
while (i < 4) : (i += 1) tmp += x[i];
break :blk tmp;
};
try expect(sum == 510);
}
```
Vectors coerce to their respective arrays.
```zig
const arr: [4]f32 = @Vector(4, f32){ 1, 2, 3, 4 };
```
It is worth noting that using explicit vectors may result in slower software if
you do not make the right decisions - the compiler's auto-vectorisation is
fairly smart as-is.
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/15.enum-ordinal-override.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
const Value2 = enum(u32) {
hundred = 100,
thousand = 1000,
million = 1000000,
next,
};
test "set enum ordinal value" {
try expect(@intFromEnum(Value2.hundred) == 100);
try expect(@intFromEnum(Value2.thousand) == 1000);
try expect(@intFromEnum(Value2.million) == 1000000);
try expect(@intFromEnum(Value2.next) == 1000001);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/08.error-union.zig | // hide-start
const expect = @import("std").testing.expect;
const FileOpenError = error{
AccessDenied,
OutOfMemory,
FileNotFound,
};
const AllocationError = error{OutOfMemory};
// hide-end
test "error union" {
const maybe_error: AllocationError!u16 = 10;
const no_error = maybe_error catch 0;
try expect(@TypeOf(no_error) == u16);
try expect(no_error == 10);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/23-optionals.md | # Optionals
Optionals use the syntax `?T` and are used to store the data
[`null`](https://ziglang.org/documentation/master/#null), or a value of type
`T`.
```zig
test "optional" {
var found_index: ?usize = null;
const data = [_]i32{ 1, 2, 3, 4, 5, 6, 7, 8, 12 };
for (data, 0..) |v, i| {
if (v == 10) found_index = i;
}
try expect(found_index == null);
}
```
Optionals support the `orelse` expression, which acts when the optional is
[`null`](https://ziglang.org/documentation/master/#null). This unwraps the
optional to its child type.
```zig
test "orelse" {
var a: ?f32 = null;
var b = a orelse 0;
try expect(b == 0);
try expect(@TypeOf(b) == f32);
}
```
`.?` is a shorthand for `orelse unreachable`. This is used for when you know it
is impossible for an optional value to be null, and using this to unwrap a
[`null`](https://ziglang.org/documentation/master/#null) value is detectable
illegal behaviour.
```zig
test "orelse unreachable" {
const a: ?f32 = 5;
const b = a orelse unreachable;
const c = a.?;
try expect(b == c);
try expect(@TypeOf(c) == f32);
}
```
Payload capturing works in many places for optionals, meaning that in the event
that it is non-null, we can "capture" its non-null value.
Here we use an `if` optional payload capture; a and b are equivalent here.
`if (b) |value|` captures the value of `b` (in the cases where `b` is not null),
and makes it available as `value`. As in the union example, the captured value
is immutable, but we can still use a pointer capture to modify the value stored
in `b`.
```zig
test "if optional payload capture" {
const a: ?i32 = 5;
if (a != null) {
const value = a.?;
_ = value;
}
var b: ?i32 = 5;
if (b) |*value| {
value.* += 1;
}
try expect(b.? == 6);
}
```
And with `while`:
```zig
var numbers_left: u32 = 4;
fn eventuallyNullSequence() ?u32 {
if (numbers_left == 0) return null;
numbers_left -= 1;
return numbers_left;
}
test "while null capture" {
var sum: u32 = 0;
while (eventuallyNullSequence()) |value| {
sum += value;
}
try expect(sum == 6); // 3 + 2 + 1
}
```
Optional pointer and optional slice types do not take up any extra memory
compared to non-optional ones. This is because internally they use the 0 value
of the pointer for `null`.
This is how null pointers in Zig work - they must be unwrapped to a non-optional
before dereferencing, which stops null pointer dereferences from happening
accidentally.
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/04.while.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
test "while" {
var i: u8 = 2;
while (i < 100) {
i *= 2;
}
try expect(i == 128);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/15.enum-ordinal.zig | // hide-start
const expect = @import("std").testing.expect;
const Value = enum(u2) { zero, one, two };
// hide-end
test "enum ordinal value" {
try expect(@intFromEnum(Value.zero) == 0);
try expect(@intFromEnum(Value.one) == 1);
try expect(@intFromEnum(Value.two) == 2);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/02-arrays.md | # Arrays
Arrays are denoted by `[N]T`, where `N` is the number of elements in the array
and `T` is the type of those elements (i.e., the array's child type).
For array literals, `N` may be replaced by `_` to infer the size of the array.
```zig
const a = [5]u8{ 'h', 'e', 'l', 'l', 'o' };
const b = [_]u8{ 'w', 'o', 'r', 'l', 'd' };
```
To get the size of an array, simply access the array's `len` field.
```zig
const array = [_]u8{ 'h', 'e', 'l', 'l', 'o' };
const length = array.len; // 5
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/19.floats-widening.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "float widening" {
const a: f16 = 0;
const b: f32 = a;
const c: f128 = b;
try expect(c == @as(f128, a));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/06.functions-recursion.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
fn fibonacci(n: u16) u16 {
if (n == 0 or n == 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
test "function recursion" {
const x = fibonacci(10);
try expect(x == 55);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.11 | repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/17-unions.mdx | import CodeBlock from "@theme/CodeBlock";
import TaggedUnion from "!!raw-loader!./17.union-tagged.zig";
# Unions
Zig's unions allow you to define types which store one value of many possible
typed fields; only one field may be active at one time.
Bare union types do not have a guaranteed memory layout. Because of this, bare
unions cannot be used to reinterpret memory. Accessing a field in a union which
is not active is detectable illegal behaviour.
```zig
const Result = union {
int: i64,
float: f64,
bool: bool,
};
test "simple union" {
var result = Result{ .int = 1234 };
result.float = 12.34;
}
```
```
test "simple union"...access of inactive union field
.\tests.zig:342:12: 0x7ff62c89244a in test "simple union" (test.obj)
result.float = 12.34;
^
```
Tagged unions are unions which use an enum to detect which field is active. Here
we make use of payload capturing again, to switch on the tag type of a union
while also capturing the value it contains. Here we use a _pointer capture_;
captured values are immutable, but with the `|*value|` syntax, we can capture a
pointer to the values instead of the values themselves. This allows us to use
dereferencing to mutate the original value.
<CodeBlock language="zig">{TaggedUnion}</CodeBlock>
The tag type of a tagged union can also be inferred. This is equivalent to the
Tagged type above.
```zig
const Tagged = union(enum) { a: u8, b: f32, c: bool };
```
`void` member types can have their type omitted from the syntax. Here, none is
of type `void`.
```zig
const Tagged2 = union(enum) { a: u8, b: f32, c: bool, none };
```
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.