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.14
repos/zig.guide/website/versioned_docs/version-0.14/01-language-basics/08.error-try.zig
// hide-start const expect = @import("std").testing.expect; fn failingFunction() error{Oops}!void { return error.Oops; } //hide-end fn failFn() error{Oops}!i32 { try failingFunction(); return 12; } test "try" { const v = failFn() catch |err| { try expect(err == error.Oops); return; }; try expect(v == 12); // is never reached }
0
repos/zig.guide/website/versioned_docs/version-0.14
repos/zig.guide/website/versioned_docs/version-0.14/01-language-basics/01.undefined.zig
const a: i32 = undefined; var b: u32 = undefined;
0
repos/zig.guide/website/versioned_docs/version-0.14
repos/zig.guide/website/versioned_docs/version-0.14/01-language-basics/23-optionals.mdx
import CodeBlock from "@theme/CodeBlock"; import OptionalsFind from "!!raw-loader!./23.optionals-find.zig"; import OptionalsOrelse from "!!raw-loader!./23.optionals-orelse.zig"; import OptionalsOrelseUnreachable from "!!raw-loader!./23.optionals-orelse-unreachable.zig"; import OptionalsIfPayload from "!!raw-loader!./23.optionals-if-payload.zig"; import OptionalsWhileCapture from "!!raw-loader!./23.optionals-while-capture.zig"; # 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`. <CodeBlock language="zig">{OptionalsFind}</CodeBlock> 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. <CodeBlock language="zig">{OptionalsOrelse}</CodeBlock> `.?` 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. <CodeBlock language="zig">{OptionalsOrelseUnreachable}</CodeBlock> Both `if` expressions and `while` loops support taking optional values as conditions, allowing you to "capture" the inner 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`. <CodeBlock language="zig">{OptionalsIfPayload}</CodeBlock> And with `while`: <CodeBlock language="zig">{OptionalsWhileCapture}</CodeBlock> 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.14
repos/zig.guide/website/versioned_docs/version-0.14/01-language-basics/15-enums.mdx
import CodeBlock from "@theme/CodeBlock"; import EnumOrdinal from "!!raw-loader!./15.enum-ordinal.zig"; import EnumOrdinalOverride from "!!raw-loader!./15.enum-ordinal-override.zig"; import EnumMethods from "!!raw-loader!./15.enum-methods.zig"; import EnumDeclarations from "!!raw-loader!./15.enum-declarations.zig"; # Enums Zig's enums allow you to define types with a restricted set of named values. Let's declare an enum. ```zig const Direction = enum { north, south, east, west }; ``` Enums types may have specified (integer) tag types. ```zig const Value = enum(u2) { zero, one, two }; ``` Enum's ordinal values start at 0. They can be accessed with the built-in function [`@intFromEnum`](https://ziglang.org/documentation/master/#intFromEnum). <CodeBlock language="zig">{EnumOrdinal}</CodeBlock> Values can be overridden, with the next values continuing from there. <CodeBlock language="zig">{EnumOrdinalOverride}</CodeBlock> Enums can be given methods. These act as namespaced functions that can be called with the dot syntax. <CodeBlock language="zig">{EnumMethods}</CodeBlock> Enums can also be given `var` and `const` declarations. These act as namespaced globals and their values are unrelated and unattached to instances of the enum type. <CodeBlock language="zig">{EnumDeclarations}</CodeBlock>
0
repos/zig.guide/website/versioned_docs/version-0.14
repos/zig.guide/website/versioned_docs/version-0.14/01-language-basics/30.vectors-coercion.zig
// hide-start const expect = @import("std").testing.expect; //hide-end const arr: [4]f32 = @Vector(4, f32){ 1, 2, 3, 4 };
0
repos/zig.guide/website/versioned_docs/version-0.14
repos/zig.guide/website/versioned_docs/version-0.14/03-build-system/04-zig-build.mdx
import CodeBlock from "@theme/CodeBlock"; import Build from "!!raw-loader!./04.zig-build-hello/build.zig"; import Hello from "!!raw-loader!./04.zig-build-hello/src/main.zig"; # Zig Build The `zig build` system allows people to do more advanced things with their Zig projects, including: - Pulling in dependencies - Building multiple artifacts (e.g. building both a static and a dynamic library) - Providing additional configuration - Doing custom tasks at build time - Building with multiple steps (e.g. fetching and processing data before compiling) The Zig build system allows you to fulfil these more complex use cases, without bringing in any additional build tools or languages (e.g. cmake, python), all while making good use of the compiler's in-built caching system. # Hello Zig Build Using the Zig build system requires writing some Zig code. Let's create a directory structure as follows. ``` . β”œβ”€β”€ build.zig └── src └── main.zig ``` Defining a build function as shown below acts as our entry point to the build system, which will allow us to define a graph of "steps" for the _build runner_ to perform. Place this code into `build.zig`. <CodeBlock language="zig">{Build}</CodeBlock> Place your executable's entry point in `src/main.zig`. <CodeBlock language="zig">{Hello}</CodeBlock> We can now run `zig build` which will output our executable. ``` $ zig build $ ./zig-out/bin/hello Hello, Zig Build! ``` # Target & Optimisation Options Previously, we've used `zig build-exe` with `-target` and `-O` to tell Zig what target and optimisation mode to use. When using the Zig build system, these settings are now passed into `b.addExecutable`. Most Zig projects will want to use these standard options. ```zig .target = b.standardTargetOptions(.{}), .optimize = b.standardOptimizeOption(.{}), ``` When using `standardTargetOptions` and `standardOptimizeOption` your target will default to native, meaning that the target of the executable will match the computer that it was built on. The optimisation mode will default to debug. If you run `zig build --help`, you can see that these functions have registered project-specific build options. ``` Project-Specific Options: -Dtarget=[string] The CPU architecture, OS, and ABI to build for -Dcpu=[string] Target CPU features to add or subtract -Doptimize=[enum] Prioritize performance, safety, or binary size (-O flag) Supported Values: Debug ReleaseSafe ReleaseFast ReleaseSmall ``` We can now supply them via arguments, e.g. ``` zig build -Dtarget=x86_64-windows -Dcpu=x86_64_v3 -Doptimize=ReleaseSafe ``` # Adding an Option Thanks to the standard target and optimise options, we already have some useful build options. In more advanced projects, you may want to add your own project-specific options; here is a basic example of creating and using an option that changes the executable's name. ```zig const exe_name = b.option( []const u8, "exe_name", "Name of the executable", ) orelse "hello"; const exe = b.addExecutable(.{ .name = exe_name, .root_source_file = .{ .path = "src/main.zig" }, .target = b.standardTargetOptions(.{}), .optimize = b.standardOptimizeOption(.{}), }); ``` If you now run `zig build --help`, we can see that the project-specific build options have been expanded to include `exe_name`. ``` Project-Specific Options: -Dexe_name=[string] Name of the executable -Dtarget=[string] The CPU architecture, OS, and ABI to build for ``` ``` $ zig build -Dtarget=x86_64-windows -Dexe_name="Hello!" $ file zig-out/bin/Hello\!.exe zig-out/bin/Hello!.exe: PE32+ executable (console) x86-64, for MS Windows, 7 sections ``` # Adding a Run Step We've previously used `zig run` as a convenient shortcut for calling `zig build-exe` and then running the resulting binary. We can quite easily do something similar using the Zig build system. ```zig b.installArtifact(exe); const run_exe = b.addRunArtifact(exe); const run_step = b.step("run", "Run the application"); run_step.dependOn(&run_exe.step); ``` ``` $ zig build run Hello, Zig Build! ``` The Zig build system uses a DAG (directed acyclic graph) of steps that it runs concurrently. Here we've created a step called "run", which depends on the `run_exe` step, which depends on our compile step. Let's have a look at the breakdown of steps in our build. ``` $ zig build run --summary all Hello, Zig Build! Build Summary: 3/3 steps succeeded run success └─ run hello success 471us MaxRSS:3M └─ zig build-exe hello Debug native success 881ms MaxRSS:220M ``` We will see more advanced build graphs as we progress.
0
repos/zig.guide/website/versioned_docs/version-0.14
repos/zig.guide/website/versioned_docs/version-0.14/03-build-system/_category_.json
{ "label": "Build System", "link": { "description": "Getting started with the Zig programming language." } }
0
repos/zig.guide/website/versioned_docs/version-0.14
repos/zig.guide/website/versioned_docs/version-0.14/03-build-system/06-generating-documentation.md
--- pagination_next: working-with-c/abi --- # Generating Documentation The Zig compiler comes with automatic documentation generation. This can be invoked by adding `-femit-docs` to your `zig build-{exe, lib, obj}` or `zig run` command. This documentation is saved into `./docs`, as a small static website. Zig's documentation generation makes use of _doc comments_ which are similar to comments, using `///` instead of `//`, and preceding globals. Here we will save this as `x.zig` and build documentation for it with `zig build-lib -femit-docs x.zig -target native-windows`. There are some things to take away here: - Only things that are public with a doc comment will appear - Blank doc comments may be used - Doc comments can make use of subset of markdown - Things will only appear inside generated documentation if the compiler analyses them; you may need to force analysis to happen to get things to appear. <!--no_test--> ```zig const std = @import("std"); const w = std.os.windows; ///**Opens a process**, giving you a handle to it. ///[MSDN](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess) pub extern "kernel32" fn OpenProcess( ///[The desired process access rights](https://docs.microsoft.com/en-us/windows/win32/procthread/process-security-and-access-rights) dwDesiredAccess: w.DWORD, /// bInheritHandle: w.BOOL, dwProcessId: w.DWORD, ) callconv(w.WINAPI) ?w.HANDLE; ///spreadsheet position pub const Pos = struct{ ///row x: u32, ///column y: u32, }; pub const message = "hello!"; //used to force analysis, as these things aren't otherwise referenced. comptime { _ = OpenProcess; _ = Pos; _ = message; } //Alternate method to force analysis of everything automatically, but only in a test build: test "Force analysis" { comptime { std.testing.refAllDecls(@This()); } } ``` When using a `build.zig` this may be invoked by setting the `emit_docs` field to `.emit` on a `CompileStep`. We can create a build step to generate docs as follows and invoke it with `$ zig build docs`. <!--no_test--> ```zig const std = @import("std"); pub fn build(b: *std.build.Builder) void { const mode = b.standardReleaseOptions(); const lib = b.addStaticLibrary("x", "src/x.zig"); lib.setBuildMode(mode); lib.install(); const tests = b.addTest("src/x.zig"); tests.setBuildMode(mode); const test_step = b.step("test", "Run library tests"); test_step.dependOn(&tests.step); //Build step to generate docs: const docs = b.addTest("src/x.zig"); docs.setBuildMode(mode); docs.emit_docs = .emit; const docs_step = b.step("docs", "Generate docs"); docs_step.dependOn(&docs.step); } ``` This generation is experimental and often fails with complex examples. This is used by the [standard library documentation](https://ziglang.org/documentation/master/std/). When merging error sets, the left-most error set's documentation strings take priority over the right. In this case, the doc comment for `C.PathNotFound` is the doc comment provided in `A`. <!--no_test--> ```zig const A = error{ NotDir, /// A doc comment PathNotFound, }; const B = error{ OutOfMemory, /// B doc comment PathNotFound, }; const C = A || B; ```
0
repos/zig.guide/website/versioned_docs/version-0.14
repos/zig.guide/website/versioned_docs/version-0.14/03-build-system/03-cross-compilation.md
# Cross-compilation By default, Zig will compile for your combination of CPU and OS. This can be overridden by `-target`. Let's compile our tiny hello world to a 64-bit arm Linux platform. `zig build-exe .\tiny-hello.zig -O ReleaseSmall -fstrip -fsingle-threaded -target aarch64-linux` [QEMU](https://www.qemu.org/) or similar may be used to conveniently test executables made for foreign platforms. Some CPU architectures that you can cross-compile for: - `x86_64` - `arm` - `aarch64` - `i386` - `riscv64` - `wasm32` Some operating systems you can cross-compile for: - `linux` - `macos` - `windows` - `freebsd` - `netbsd` - `dragonfly` - `UEFI` Many other targets are available for compilation but aren't as well tested as of now. See [Zig's support table](https://ziglang.org/learn/overview/#wide-range-of-targets-supported) for more information; the list of well-tested targets is slowly expanding. As Zig compiles for your specific CPU by default, these binaries may not run on other computers with slightly different CPU architectures. It may be useful to instead specify a specific baseline CPU model for greater compatibility. Note: Choosing an older CPU architecture will bring greater compatibility, but means you also miss out on newer CPU instructions; there is an efficiency/speed versus compatibility trade-off here. Let's compile a binary for a sandybridge CPU (Intel x86_64, circa 2011), so we can be reasonably sure that someone with an x86_64 CPU can run our binary. Here we can use `native` in place of our CPU or OS, to use our system's. `zig build-exe tiny-hello.zig -target x86_64-native -mcpu sandybridge` Details on what architectures, OSes, CPUs, and ABIs (details on ABIs in the next chapter) are available can be found by running `zig targets`. Note: the output is long, and you may want to pipe it to a file, e.g. `zig targets > targets.json`.
0
repos/zig.guide/website/versioned_docs/version-0.14
repos/zig.guide/website/versioned_docs/version-0.14/03-build-system/02-emitting-an-executable.md
# Emitting an Executable The commands `zig build-exe`, `zig build-lib`, and `zig build-obj` can be used to output executables, libraries, and objects, respectively. These commands take in a source file and arguments. Some common arguments: - `-fsingle-threaded`, which asserts the binary is single-threaded. This will turn thread-safety measures such as mutexes into no-ops. - `-fstrip`, which removes debug info from the binary. - `--dynamic`, which is used in conjunction with `zig build-lib` to output a dynamic/shared library. Let's create a tiny hello world. Save this as `tiny-hello.zig`, and run `zig build-exe tiny-hello.zig -O ReleaseSmall -fstrip -fsingle-threaded`. ```zig const std = @import("std"); pub fn main() void { std.io.getStdOut().writeAll( "Hello World!", ) catch unreachable; } ```
0
repos/zig.guide/website/versioned_docs/version-0.14
repos/zig.guide/website/versioned_docs/version-0.14/03-build-system/01-build-modes.md
--- pagination_prev: standard-library/advanced-formatting --- # Build Modes Zig provides four build modes, with debug being the default as it produces the shortest compile times. | | Runtime Safety | Optimizations | | ------------ | -------------- | ------------- | | Debug | Yes | No | | ReleaseSafe | Yes | Yes, Speed | | ReleaseSmall | No | Yes, Size | | ReleaseFast | No | Yes, Speed | These may be used with `zig run` and `zig test` with the arguments `-O ReleaseSafe`, `-O ReleaseSmall`, and `-O ReleaseFast`. Users are recommended to develop their software with runtime safety enabled, despite its small speed disadvantage.
0
repos/zig.guide/website/versioned_docs/version-0.14/03-build-system
repos/zig.guide/website/versioned_docs/version-0.14/03-build-system/04.zig-build-hello/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const exe = b.addExecutable(.{ .name = "hello", .root_source_file = .{ .path = "src/main.zig" }, .target = b.standardTargetOptions(.{}), .optimize = b.standardOptimizeOption(.{}), }); b.installArtifact(exe); }
0
repos/zig.guide/website/versioned_docs/version-0.14/03-build-system/04.zig-build-hello
repos/zig.guide/website/versioned_docs/version-0.14/03-build-system/04.zig-build-hello/src/main.zig
const std = @import("std"); pub fn main() void { std.debug.print("Hello, {s}!\n", .{"Zig Build"}); }
0
repos/zig.guide/website/versioned_docs/version-0.14
repos/zig.guide/website/versioned_docs/version-0.14/04-working-with-c/02-c-primitive-types.md
# C Primitive Types Zig provides special `c_` prefixed types for conforming to the C ABI. These do not have fixed sizes but rather change in size depending on the ABI being used. | Type | C Equivalent | Minimum Size (bits) | | ------------ | ------------------ | ------------------- | | c_short | short | 16 | | c_ushort | unsigned short | 16 | | c_int | int | 16 | | c_uint | unsigned int | 16 | | c_long | long | 32 | | c_ulong | unsigned long | 32 | | c_longlong | long long | 64 | | c_ulonglong | unsigned long long | 64 | | c_longdouble | long double | N/A | | anyopaque | void | N/A | Note: C's void (and Zig's `anyopaque`) has an unknown non-zero size. Zig's `void` is a true zero-sized type.
0
repos/zig.guide/website/versioned_docs/version-0.14
repos/zig.guide/website/versioned_docs/version-0.14/04-working-with-c/03-calling-conventions.md
# Calling conventions Calling conventions describe how functions are called. This includes how arguments are supplied to the function (i.e. where they go - in registers or on the stack, and how), and how the return value is received. In Zig, the attribute `callconv` may be given to a function. The calling conventions available may be found in [std.builtin.CallingConvention](https://ziglang.org/documentation/master/std/#std.builtin.CallingConvention). Here we make use of the cdecl calling convention. ```zig fn add(a: u32, b: u32) callconv(.C) u32 { return a + b; } ``` Marking your functions with the C calling convention is crucial when you're calling Zig from C.
0
repos/zig.guide/website/versioned_docs/version-0.14
repos/zig.guide/website/versioned_docs/version-0.14/04-working-with-c/06-packed-structs.md
# Packed Structs By default, all struct fields in Zig are naturally aligned to that of [`@alignOf(FieldType)`](https://ziglang.org/documentation/master/#alignOf) (the ABI size), but without a defined layout. Sometimes you may want to have struct fields with a defined layout that do not conform to your C ABI. `packed` structs allow you to have extremely precise control of your struct fields, allowing you to place your fields on a bit-by-bit basis. Inside packed structs, Zig's integers take their bit-width in space (i.e. a `u12` has an [`@bitSizeOf`](https://ziglang.org/documentation/master/#bitSizeOf) of 12, meaning it will take up 12 bits in the packed struct). Bools also take up 1 bit, meaning you can implement bit flags easily. ```zig const MovementState = packed struct { running: bool, crouching: bool, jumping: bool, in_air: bool, }; test "packed struct size" { try expect(@sizeOf(MovementState) == 1); try expect(@bitSizeOf(MovementState) == 4); const state = MovementState{ .running = true, .crouching = true, .jumping = true, .in_air = true, }; _ = state; } ```
0
repos/zig.guide/website/versioned_docs/version-0.14
repos/zig.guide/website/versioned_docs/version-0.14/04-working-with-c/12-zig-cc.md
--- pagination_next: async/introduction --- # Zig cc, Zig c++ The Zig executable comes with Clang embedded inside it alongside libraries and headers required to cross-compile for other operating systems and architectures. This means that not only can `zig cc` and `zig c++` compile C and C++ code (with Clang-compatible arguments), but it can also do so while respecting Zig's target triple argument; the single Zig binary that you have installed has the power to compile for several different targets without the need to install multiple versions of the compiler or any addons. Using `zig cc` and `zig c++` also makes use of Zig's caching system to speed up your workflow. Using Zig, one can easily construct a cross-compiling toolchain for languages that use a C and/or C++ compiler. Some examples in the wild: - [Using zig cc to cross compile LuaJIT to aarch64-linux from x86_64-linux](https://andrewkelley.me/post/zig-cc-powerful-drop-in-replacement-gcc-clang.html) - [Using zig cc and zig c++ in combination with cgo to cross compile hugo from aarch64-macos to x86_64-linux, with full static linking](https://twitter.com/croloris/status/1349861344330330114)
0
repos/zig.guide/website/versioned_docs/version-0.14
repos/zig.guide/website/versioned_docs/version-0.14/04-working-with-c/_category_.json
{ "label": "Working with C", "link": { "description": "Zig has been designed from the ground up with C interop as a first-class feature. In this section, we will go over how this works." } }
0
repos/zig.guide/website/versioned_docs/version-0.14
repos/zig.guide/website/versioned_docs/version-0.14/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.14
repos/zig.guide/website/versioned_docs/version-0.14/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.14
repos/zig.guide/website/versioned_docs/version-0.14/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.14
repos/zig.guide/website/versioned_docs/version-0.14/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.14
repos/zig.guide/website/versioned_docs/version-0.14/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.14
repos/zig.guide/website/versioned_docs/version-0.14/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.14
repos/zig.guide/website/versioned_docs/version-0.14/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.14
repos/zig.guide/website/versioned_docs/version-0.14/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.14
repos/zig.guide/website/versioned_docs/version-0.14/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.14
repos/zig.guide/website/versioned_docs/version-0.14/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.14
repos/zig.guide/website/versioned_docs/version-0.14/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.14
repos/zig.guide/website/versioned_docs/version-0.14/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.14
repos/zig.guide/website/versioned_docs/version-0.14/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.14
repos/zig.guide/website/versioned_docs/version-0.14/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/05-async/01-introduction.md
--- pagination_prev: working-with-c/zig-cc --- # Introduction :::danger Zig's async features have not been present in the compiler for multiple major versions. There is currently no estimate on when async will be added back to the compiler; async's future is unclear. The following code will not compile with Zig 0.11 or Zig 0.12. ::: 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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/02-standard-library/07.random-numbers.zig
// hide-start const std = @import("std"); // hide-end test "random numbers" { var prng = std.rand.DefaultPrng.init(blk: { var seed: u64 = undefined; try std.posix.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 }; }
0
repos/zig.guide/website/versioned_docs/version-0.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/02-standard-library/13.iterators-custom.zig
// hide-start const std = @import("std"); const eql = std.mem.eql; const expect = std.testing.expect; // hide-end 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.13
repos/zig.guide/website/versioned_docs/version-0.13/02-standard-library/13.iterators-looping.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; // hide-end test "iterator looping" { var iter = (try std.fs.cwd().openDir( ".", .{ .iterate = true }, )).iterate(); var file_count: usize = 0; while (try iter.next()) |entry| { if (entry.kind == .file) file_count += 1; } try expect(file_count > 0); }
0
repos/zig.guide/website/versioned_docs/version-0.13
repos/zig.guide/website/versioned_docs/version-0.13/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. When the Enum type is known from context, it can be omitted, so we can compare `stat.kind` to `.file` instead of `Kind.file`. <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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/02-standard-library/13-iterators.mdx
import CodeBlock from "@theme/CodeBlock"; import IteratorsSplit from "!!raw-loader!./13.iterators-split.zig"; import IteratorsLooping from "!!raw-loader!./13.iterators-looping.zig"; import IteratorsCustom from "!!raw-loader!./13.iterators-custom.zig"; # 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. <CodeBlock language="zig">{IteratorsSplit}</CodeBlock> 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 for the directory iterator to work. <CodeBlock language="zig">{IteratorsLooping}</CodeBlock> Here we will implement a custom iterator. This will iterate over a slice of strings, yielding the strings which contain a given string. <CodeBlock language="zig">{IteratorsCustom}</CodeBlock>
0
repos/zig.guide/website/versioned_docs/version-0.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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; } @memcpy( self.data[self.items.len..][0..data.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.13
repos/zig.guide/website/versioned_docs/version-0.13/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 that 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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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 that 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.13
repos/zig.guide/website/versioned_docs/version-0.13/02-standard-library/13.iterators-split.zig
// hide-start const std = @import("std"); const eql = std.mem.eql; const expect = std.testing.expect; // hide-end 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); }
0
repos/zig.guide/website/versioned_docs/version-0.13
repos/zig.guide/website/versioned_docs/version-0.13/02-standard-library/07.random-numbers-crypto.zig
// hide-start const std = @import("std"); // hide-end 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 }; }
0
repos/zig.guide/website/versioned_docs/version-0.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/02-standard-library/06.json-parse.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; const test_allocator = std.testing.allocator; // hide-end 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); }
0
repos/zig.guide/website/versioned_docs/version-0.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/02-standard-library/06-json.mdx
import CodeBlock from "@theme/CodeBlock"; import JsonParse from "!!raw-loader!./06.json-parse.zig"; import JsonStringify from "!!raw-loader!./06.json-stringify.zig"; import JsonStringifyStrings from "!!raw-loader!./06.json-stringify-strings.zig"; # JSON Let's parse a JSON string into a struct type, using the streaming parser. <CodeBlock language="zig">{JsonParse}</CodeBlock> And using stringify to turn arbitrary data into a string. <CodeBlock language="zig">{JsonStringify}</CodeBlock> The JSON parser requires an allocator for javascript's string, array, and map types. <CodeBlock language="zig">{JsonStringifyStrings}</CodeBlock>
0
repos/zig.guide/website/versioned_docs/version-0.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/02-standard-library/06.json-stringify.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; const test_allocator = std.testing.allocator; const Place = struct { lat: f32, long: f32 }; // hide-end 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.199766540527344e1,"long":-7.406870126724243e-1} )); }
0
repos/zig.guide/website/versioned_docs/version-0.13
repos/zig.guide/website/versioned_docs/version-0.13/02-standard-library/07-random-numbers.mdx
import CodeBlock from "@theme/CodeBlock"; import RandomNumbers from "!!raw-loader!./07.random-numbers.zig"; import RandomNumbersCrypto from "!!raw-loader!./07.random-numbers-crypto.zig"; # 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. <CodeBlock language="zig">{RandomNumbers}</CodeBlock> Cryptographically secure random is also available. <CodeBlock language="zig">{RandomNumbersCrypto}</CodeBlock> :::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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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().openDir( "test-tmp", .{ .iterate = true }, ); defer { iter_dir.close(); std.fs.cwd().deleteTree("test-tmp") catch unreachable; } _ = try iter_dir.createFile("x", .{}); _ = try iter_dir.createFile("y", .{}); _ = try iter_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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/02-standard-library/06.json-stringify-strings.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 "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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/24.comptime-typeinfo.zig
// hide-start const expect = @import("std").testing.expect; //hide-end fn addSmallInts(comptime T: type, a: T, b: T) T { return switch (@typeInfo(T)) { .ComptimeInt => a + b, .Int => |info| if (info.bits <= 16) a + b else @compileError("ints too large"), else => @compileError("only ints accepted"), }; } test "typeinfo switch" { const x = addSmallInts(u16, 20, 30); try expect(@TypeOf(x) == u16); try expect(x == 50); }
0
repos/zig.guide/website/versioned_docs/version-0.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/23.optionals-orelse-unreachable.zig
// hide-start const expect = @import("std").testing.expect; //hide-end test "orelse unreachable" { const a: ?f32 = 5; const b = a orelse unreachable; const c = a.?; try expect(b == c); try expect(@TypeOf(c) == f32); }
0
repos/zig.guide/website/versioned_docs/version-0.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/25.payload-captures-optional-if.zig
// hide-start const expect = @import("std").testing.expect; //hide-end test "optional-if" { const maybe_num: ?usize = 10; if (maybe_num) |n| { try expect(@TypeOf(n) == usize); try expect(n == 10); } else { unreachable; } }
0
repos/zig.guide/website/versioned_docs/version-0.13
repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/08.error-set.zig
const FileOpenError = error{ AccessDenied, OutOfMemory, FileNotFound, };
0
repos/zig.guide/website/versioned_docs/version-0.13
repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/30.vectors-looping.zig
// hide-start const expect = @import("std").testing.expect; //hide-end test "vector looping" { const x = @Vector(4, u8){ 255, 0, 255, 0 }; const 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); }
0
repos/zig.guide/website/versioned_docs/version-0.13
repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/24.comptime-ints.zig
// hide-start const expect = @import("std").testing.expect; //hide-end test "comptime_int" { const a = 12; const b = a + 10; const c: u4 = a; const d: f32 = b; try expect(c == 12); try expect(d == 22); }
0
repos/zig.guide/website/versioned_docs/version-0.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/25.payload-captures-error-union-if.zig
// hide-start const expect = @import("std").testing.expect; //hide-end test "error union if" { const ent_num: error{UnknownEntity}!u32 = 5; if (ent_num) |entity| { try expect(@TypeOf(entity) == u32); try expect(entity == 5); } else |err| { _ = err catch {}; unreachable; } }
0
repos/zig.guide/website/versioned_docs/version-0.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/29.sentinel-termination-string-literal.zig
// hide-start const expect = @import("std").testing.expect; //hide-end test "string literal" { try expect(@TypeOf("hello") == *const [5:0]u8); }
0
repos/zig.guide/website/versioned_docs/version-0.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/24-comptime.mdx
import CodeBlock from "@theme/CodeBlock"; import ComptimeBlocks from "!!raw-loader!./24.comptime-blocks.zig"; import ComptimeInts from "!!raw-loader!./24.comptime-ints.zig"; import ComptimeTypeBranching from "!!raw-loader!./24.comptime-type-branching.zig"; import ComptimeReturningType from "!!raw-loader!./24.comptime-returning-type.zig"; import ComptimeTypeinfo from "!!raw-loader!./24.comptime-typeinfo.zig"; import ComptimeType from "!!raw-loader!./24.comptime-type.zig"; import ComptimeReturnStruct from "!!raw-loader!./24.comptime-return-struct.zig"; import ComptimeAnytype from "!!raw-loader!./24.comptime-anytype.zig"; import ComptimeConcatRepeat from "!!raw-loader!./24.comptime-concat-repeat.zig"; # Comptime Blocks of code may be forcibly executed at compile time using the [`comptime`](https://ziglang.org/documentation/master/#comptime) keyword. In this example, the variables x and y are equivalent. <CodeBlock language="zig">{ComptimeBlocks}</CodeBlock> Integer literals are of the type `comptime_int`. These are special in that they have no size (they cannot be used at runtime!), and they have arbitrary precision. `comptime_int` values coerce to any integer type that can hold them. They also coerce to floats. Character literals are of this type. <CodeBlock language="zig">{ComptimeInts}</CodeBlock> `comptime_float` is also available, which internally is an `f128`. These cannot be coerced to integers, even if they hold an integer value. Types in Zig are values of the type `type`. These are available at compile time. We have previously encountered them by checking [`@TypeOf`](https://ziglang.org/documentation/master/#TypeOf) and comparing with other types, but we can do more. <CodeBlock language="zig">{ComptimeTypeBranching}</CodeBlock> Function parameters in Zig can be tagged as being [`comptime`](https://ziglang.org/documentation/master/#comptime). This means that the value passed to that function parameter must be known at compile time. Let's make a function that returns a type. Notice how this function is PascalCase, as it returns a type. <CodeBlock language="zig">{ComptimeReturningType}</CodeBlock> We can reflect upon types using the built-in [`@typeInfo`](https://ziglang.org/documentation/master/#typeInfo), which takes in a `type` and returns a tagged union. This tagged union type can be found in [`std.builtin.Type`](https://ziglang.org/documentation/master/std/#std.builtin.Type) (info on how to make use of imports and std later). <CodeBlock language="zig">{ComptimeTypeinfo}</CodeBlock> We can use the [`@Type`](https://ziglang.org/documentation/master/#Type) function to create a type from a [`@typeInfo`](https://ziglang.org/documentation/master/#typeInfo). [`@Type`](https://ziglang.org/documentation/master/#Type) is implemented for most types but is notably unimplemented for enums, unions, functions, and structs. Here anonymous struct syntax is used with `.{}`, because the `T` in `T{}` can be inferred. Anonymous structs will be covered in detail later. In this example we will get a compile error if the `Int` tag isn't set. <CodeBlock language="zig">{ComptimeType}</CodeBlock> Returning a struct type is how you make generic data structures in Zig. The usage of [`@This`](https://ziglang.org/documentation/master/#This) is required here, which gets the type of the innermost struct, union, or enum. Here [`std.mem.eql`](https://ziglang.org/documentation/master/std/#std;mem.eql) is also used which compares two slices. <CodeBlock language="zig">{ComptimeReturnStruct}</CodeBlock> The types of function parameters can also be inferred by using `anytype` in place of a type. [`@TypeOf`](https://ziglang.org/documentation/master/#TypeOf) can then be used on the parameter. <CodeBlock language="zig">{ComptimeAnytype}</CodeBlock> Comptime also introduces the operators `++` and `**` for concatenating and repeating arrays and slices. These operators do not work at runtime. <CodeBlock language="zig">{ComptimeConcatRepeat}</CodeBlock>
0
repos/zig.guide/website/versioned_docs/version-0.13
repos/zig.guide/website/versioned_docs/version-0.13/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.13
repos/zig.guide/website/versioned_docs/version-0.13/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.