### Printing 'Hello World' to StdOut in Zig Source: https://zig.guide/standard-library/formatting Shows a basic example of printing 'Hello, World!' to standard output using `std.io.getStdOut().writer().print`. This demonstrates the fundamental mechanism for console output in Zig. ```zig const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; test "hello world" { const out_file = std.io.getStdOut(); try out_file.writer().print( "Hello, {s}!\n", ,{ "World"}, ); } ``` -------------------------------- ### Setup stdin and stdout for interactive use in Zig Source: https://zig.guide/posts/a-guessing-game Sets up both standard input and standard output readers/writers for interactive console applications. This is essential for games or tools that require user input and provide feedback. ```zig var stdout_buf: [1024]u8 = undefined; var stdout_writer = std.fs.File.stdout().writer(&stdout_buf); const stdout: *std.io.Writer = &stdout_writer.interface; var stdin_buf: [1024]u8 = undefined; var stdin_reader = std.fs.File.stdin().reader(&stdin_buf); const stdin: *std.io.Reader = &stdin_reader.interface; while (true) { defer stdout.flush() catch {}; ``` -------------------------------- ### Initialize Game State and Input/Output in Zig Source: https://zig.guide/posts/a-guessing-game Sets up the game by initializing a random seed, generating a target number, and configuring standard input and output writers. This function is essential for starting the game's logic. ```zig const std = @import("std"); pub fn main() !void { var seed: u64 = undefined; try std.posix.getrandom(std.mem.asBytes(&seed)); var prng: std.Random.DefaultPrng = .init(seed); const rand = prng.random(); const target_number = rand.intRangeAtMost(u8, 1, 100); var stdout_buf: [1024]u8 = undefined; var stdout_writer = std.fs.File.stdout().writer(&stdout_buf); const stdout: *std.io.Writer = &stdout_writer.interface; var stdin_buf: [1024]u8 = undefined; var stdin_reader = std.fs.File.stdin().reader(&stdin_buf); const stdin: *std.io.Reader = &stdin_reader.interface; while (true) { defer stdout.flush() catch {}; const bare_line = try stdin.takeDelimiter('\n') orelse unreachable; const line = std.mem.trim(u8, bare_line, "\r"); ``` -------------------------------- ### Zig: Hello World Executable Example Source: https://zig.guide/0.13/build-system/emitting-an-executable A simple 'Hello World!' program in Zig that writes to standard output. It demonstrates the basic structure for creating an executable using Zig's standard library for I/O. This example is compiled with optimization and flags to reduce binary size and enforce single-threaded execution. ```zig const std = @import("std"); pub fn main() void { std.io.getStdOut().writeAll( "Hello World!", ) catch unreachable; } ``` -------------------------------- ### Install Zig with Scoop Source: https://zig.guide/0.11/getting-started/installation This command uses the Scoop package manager to install Zig on Windows. Scoop is a command-line installer for applications. ```powershell scoop install zig ``` -------------------------------- ### Guessing Game Setup in Zig Source: https://zig.guide/posts This Zig code snippet is the beginning of a guessing game program. It sets up the necessary components for generating a random number and receiving user input. As Zig lacks a built-in runtime, this section focuses on manually initializing a pseudo-random number generator. ```Zig const std = @import("std"); // Placeholder for random number generation setup ``` -------------------------------- ### Write to Stdout in Zig Source: https://zig.guide/posts/tags/zig-0-15-x Demonstrates how to obtain a writer for standard output in Zig and flush it. This is a fundamental step for any program that needs to print information to the console. It initializes a buffer and a writer interface for stdout. ```zig const std = @import("std"); pub fn main() !void { var stdout_buf: [1024]u8 = undefined; var stdout_writer = std.fs.File.stdout().writer(&stdout_buf); const stdout = &stdout_writer.interface; defer stdout.flush() catch {}; ``` -------------------------------- ### Zig Switch Statement Example Source: https://zig.guide/0.13/language-basics/switch Demonstrates the usage of a switch statement in Zig. It shows how to handle different cases and includes an 'else' block for exhaustive checking. This example requires the testing module. ```zig const expect = @import("std").testing.expect; test "switch statement" { var x: i8 = 10; switch (x) { -1...1 => { x = -x; }, 10, 100 => { //special considerations must be made //when dividing signed integers x = @divExact(x, 10); }, else => {}, } try expect(x == 1); } ``` -------------------------------- ### Install Zig with Winget Source: https://zig.guide/0.11/getting-started/installation This command uses the Windows Package Manager (winget) to install Zig. It's a native package manager for Windows, often available by default. ```powershell winget install zig.zig ``` -------------------------------- ### Zig Build System for Documentation Generation Source: https://zig.guide/0.13/build-system/generating-documentation This Zig build script illustrates how to integrate documentation generation into the build process. It defines a static library, installs its artifacts, and then creates a separate step to install the generated documentation into a specified subdirectory. ```zig const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const lib = b.addStaticLibrary(.{ .name = "lib", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); b.installArtifact(lib); const install_docs = b.addInstallDirectory(.{ .source_dir = lib.getEmittedDocs(), .install_dir = .prefix, .install_subdir = "docs", }); const docs_step = b.step("docs", "Install docs into zig-out/docs"); docs_step.dependOn(&install_docs.step); } ``` -------------------------------- ### Zig Switch Statement Example Source: https://zig.guide/0.12/language-basics/switch Demonstrates the usage of a switch statement in Zig. It shows how to handle different integer ranges and values, including the use of an 'else' block for exhaustiveness. This example is part of the Zig 0.12.0 documentation. ```zig const expect = @import("std").testing.expect; test "switch statement" { var x: i8 = 10; switch (x) { -1...1 => { x = -x; }, 10, 100 => { //special considerations must be made //when dividing signed integers x = @divExact(x, 10); }, else => {}, } try expect(x == 1); } ``` -------------------------------- ### Zig: Example of Position Usage in String Formatting Source: https://zig.guide/0.12/standard-library/advanced-formatting Demonstrates how to use argument positions within format strings in Zig. This example shows inserting multiple arguments using their index. ```zig test "position" { var b: [3]u8 = undefined; try expect(eql( u8, try bufPrint(&b, "{0s}{0s}{1s}", .{ "a", "b" }), "aab", )); } ``` -------------------------------- ### Default Formatting with '{any}' in Zig Source: https://zig.guide/standard-library/formatting Explains and demonstrates the use of the `{any}` format specifier for default printing of arbitrary types. This is contrasted with `{s}` for strings and shows how arrays are printed by default. ```zig const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; const test_allocator = std.testing.allocator; 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 }", )); } ``` -------------------------------- ### Generate Documentation with Zig Build Source: https://zig.guide/build-system/generating-documentation This snippet shows how to configure a `build.zig` file to generate and install documentation for a static library. It uses `b.addStaticLibrary` to define the library and `lib.getEmittedDocs()` to access the generated documentation files, which are then installed via `b.addInstallDirectory`. ```zig const std = @import("std"); public fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const lib = b.addStaticLibrary(.{ .name = "lib", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); b.installArtifact(lib); const install_docs = b.addInstallDirectory(.{ .source_dir = lib.getEmittedDocs(), .install_dir = .prefix, .install_subdir = "docs", }); const docs_step = b.step("docs", "Install docs into zig-out/docs"); docs_step.dependOn(&install_docs.step); } ``` -------------------------------- ### Zig Build: Define Executable and Install Artifact Source: https://zig.guide/0.12/build-system/zig-build Defines an executable with a root source file and standard target/optimization options, then installs it as a build artifact. This is a fundamental step in configuring a Zig project's build process. ```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); } ``` -------------------------------- ### Zig Arena Allocator Example Source: https://zig.guide/0.12/standard-library/allocators Shows how to use `std.heap.ArenaAllocator` to allocate memory and free it all at once upon deinitialization. This is efficient when multiple allocations are made and then released together. ```zig const std = @import("std"); const expect = std.testing.expect; 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); } ``` -------------------------------- ### Zig: Suspend with Resume Example Source: https://zig.guide/0.13/async/suspend-resume Illustrates a well-formed Zig async function that correctly uses 'suspend' followed by 'resume'. This ensures that control flow is properly managed, allowing the suspended function to continue execution after being resumed by the caller. The example shows the expected order of operations and state changes. ```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 } ``` -------------------------------- ### Install Zig with Chocolatey Source: https://zig.guide/0.11/getting-started/installation This command uses the Chocolatey package manager to install Zig on Windows. It's a simple way to get Zig if Chocolatey is already set up on the system. ```powershell choco install zig ``` -------------------------------- ### Get Windows CPU Architecture Source: https://zig.guide/0.11/getting-started/installation This PowerShell command retrieves the processor architecture of the current process, which helps in determining the correct Zig version to download for Windows. ```powershell $Env:PROCESSOR_ARCHITECTURE ``` -------------------------------- ### Zig Hello World Program (Zig 0.12.0) Source: https://zig.guide/0.12/getting-started/hello-world A basic 'Hello World' program in Zig 0.12.0. This snippet demonstrates the fundamental structure of a Zig program, including importing the standard library and printing output. The program assumes UTF-8 encoding for the source file. ```zig const std = @import("std"); pub fn main() void { std.debug.print("Hello, {s}!\n", .{"World\n"}); } ``` -------------------------------- ### Get Linux CPU Architecture Source: https://zig.guide/0.11/getting-started/installation This command retrieves the machine hardware and software platform, typically used to identify the CPU architecture for downloading the correct Zig binary on Linux. ```shell uname -m ``` -------------------------------- ### Summarize Build Steps with Zig Build CLI Source: https://zig.guide/build-system/zig-build This command shows how to use the `--summary all` flag with the Zig build system to visualize the execution order and dependencies of build steps. It provides a detailed breakdown of the 'run' step and its sub-steps. ```bash $ 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 ``` -------------------------------- ### Zig Async/Await Example Source: https://zig.guide/0.12/async/async-await Demonstrates the use of async/await in Zig. It shows how to call an async function and await its result, and how a normal function can be used within an async context. The test verifies the returned value. ```zig fn func3() u32 { return 5; } test "async / await" { var frame = async func3(); try expect(await frame == 5); } ``` -------------------------------- ### Verify Zig Installation Source: https://zig.guide/0.11/getting-started/installation This command checks the currently installed Zig version. Running `zig version` in the terminal should output the version number, confirming a successful installation. ```shell zig version ``` -------------------------------- ### Printing Hello World using std.io.getStdOut Source: https://zig.guide/0.13/standard-library/formatting A basic example of printing 'Hello, World!' to standard output. It utilizes the `print` method on the standard output writer and the `{s}` format specifier for strings. ```zig const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; test "hello world" { const out_file = std.io.getStdOut(); try out_file.writer().print( "Hello, {s}!\n", .{"World"}, ); } ``` -------------------------------- ### Install Zig with Homebrew Source: https://zig.guide/0.11/getting-started/installation This command uses the Homebrew package manager to install Zig on macOS. Homebrew is a popular package manager for macOS. ```shell brew install zig ``` -------------------------------- ### Add Zig to System PATH (Windows) Source: https://zig.guide/0.13/getting-started/installation This PowerShell command adds the Zig installation directory to the system-wide PATH environment variable. Ensure 'C:\_\zig-windows-_' is replaced with your actual Zig installation path. ```powershell [Environment]::SetEnvironmentVariable("Path", [Environment]::GetEnvironmentVariable("Path", "Machine") + ";C:\_\zig-windows-_", "Machine") ``` -------------------------------- ### Zig Hello World Program Source: https://zig.guide/0.11/getting-started/hello-world A simple Zig program that prints 'Hello, World!' to standard error. This example demonstrates basic Zig syntax, including importing the standard library and defining the main function. Ensure your source file is UTF-8 encoded. ```zig const std = @import("std"); pub fn main() void { std.debug.print("Hello, {s}!\n", .{"World"}); } ``` -------------------------------- ### Add Zig to User PATH (Windows) Source: https://zig.guide/0.13/getting-started/installation This PowerShell command adds the Zig installation directory to the current user's PATH environment variable. Ensure 'C:\_\zig-windows-_' is replaced with your actual Zig installation path. ```powershell [Environment]::SetEnvironmentVariable("Path", [Environment]::GetEnvironmentVariable("Path", "User") + ";C:\_\zig-windows-_", "User") ``` -------------------------------- ### Create Executable with CompileStep in Zig Source: https://zig.guide/0.11/build-system/compilestep Demonstrates how to create a CompileStep for an executable using Zig's build system. This involves initializing a Builder, adding an executable with its name and root source file, and then installing the artifact. Dependencies include the standard library's build module. ```zig const Builder = @import("std").build.Builder; pub fn build(b: *Builder) void { const exe = b.addExecutable(.{ .name = "init-exe", .root_source_file = .{ .path = "src/main.zig" }, }); b.installArtifact(exe); } ``` -------------------------------- ### Add Zig to Windows System PATH Source: https://zig.guide/0.11/getting-started/installation This PowerShell script adds the specified Zig installation directory to the system-wide PATH environment variable. This makes Zig accessible to all users on the machine. ```powershell [Environment]::SetEnvironmentVariable("Path", [Environment]::GetEnvironmentVariable("Path", "Machine") + ";C:\\_\zig-windows-_", "Machine") ``` -------------------------------- ### Add Zig to Windows User PATH Source: https://zig.guide/0.11/getting-started/installation This PowerShell script adds the specified Zig installation directory to the current user's PATH environment variable. This allows Zig to be accessed from any command prompt or PowerShell session without needing to specify the full path. ```powershell [Environment]::SetEnvironmentVariable("Path", [Environment]::GetEnvironmentVariable("Path", "User") + ";C:\\_\zig-windows-_", "User") ``` -------------------------------- ### Apply Linux PATH Changes Source: https://zig.guide/0.13/getting-started/installation This command reloads the `.bashrc` file for the current terminal session, making the changes to the PATH effective immediately. ```shell source ~/.bashrc ``` -------------------------------- ### Extract Zig Archive on Linux Source: https://zig.guide/0.13/getting-started/installation This command uses `tar` to extract the downloaded Zig archive on Linux. Replace the filename with the specific version and architecture you downloaded. ```shell tar xf zig-linux-x86_64-0.13.0.tar.xz ``` -------------------------------- ### Zig Split Iterator Example Source: https://zig.guide/standard-library/iterators Demonstrates the use of `std.mem.splitSequence` to iterate over a string, splitting it by a delimiter. It uses `iter.next().?` to access the next element, returning null when iteration is complete. ```zig const std = @import("std"); const eql = std.mem.eql; const expect = std.testing.expect; test "split iterator" { const text = "robust, optimal, reusable, maintainable, "; var iter = std.mem.splitSequence(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); } ``` -------------------------------- ### View build summary with the 'run' step Source: https://zig.guide/0.13/build-system/zig-build This command shows the build summary after executing the 'run' step, detailing the success of each step in the build graph and the time taken. ```bash $ 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 ``` -------------------------------- ### String Keys with StringHashMap in Zig Source: https://zig.guide/standard-library/hashmaps Demonstrates using `std.StringHashMap` for hash maps where keys are strings. This example shows how to insert string keys with an enum value type and retrieve them. Requires an allocator. ```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); } ``` -------------------------------- ### Zig: Create Directory and Iterate Contents Source: https://zig.guide/0.13/standard-library/filesystem Demonstrates creating a temporary directory, adding files to it, iterating through the directory's contents, and then cleaning up by deleting the directory and its files. It uses iterators for directory traversal. ```zig const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; 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); } ``` -------------------------------- ### Initialize Zig Project and Add Module Source: https://zig.guide/0.11/build-system/modules Commands to initialize a new Zig executable project, create a 'libs' directory, and clone the 'table-helper' module into it. This sets up the basic project structure for using external modules. ```bash zig init-exe cd .. mkdir libs cd libs git clone https://github.com/Sobeston/table-helper.git ``` -------------------------------- ### Zig Iterator Looping with Error Handling Source: https://zig.guide/standard-library/iterators Shows how to loop through directory entries using an iterator that returns an error union (`!?T`). This example opens the current directory with iterate permissions and counts the number of files. ```zig const std = @import("std"); const expect = std.testing.expect; test "iterator looping" { var cwd = try std.fs.cwd().openDir(".", .{ .iterate = true, }); defer cwd.close(); var file_count: usize = 0; var iter = cwd.iterate(); while (try iter.next()) |entry| { if (entry.kind == .file) file_count += 1; } try expect(file_count > 0); } ``` -------------------------------- ### Zig Hello World Executable Source: https://zig.guide/0.11/build-system/emitting-an-executable A simple Zig program that prints 'Hello World!' to standard output. This snippet demonstrates basic I/O operations and is intended to be compiled into an executable using the 'zig build-exe' command with optimization and stripping flags. ```zig const std = @import("std"); pub fn main() void { std.io.getStdOut().writeAll( "Hello World!", ) catch unreachable; } ``` -------------------------------- ### Get Process Arguments in Zig Source: https://zig.guide/posts/fahrenheit-to-celsius Retrieves command-line arguments passed to a Zig program using `std.process.argsAlloc`. It utilizes the `std.heap.page_allocator` for memory allocation and includes error handling for potential allocation failures. ```zig const args = try std.process.argsAlloc(std.heap.page_allocator); ``` -------------------------------- ### Zig Allocator Create/Destroy Example Source: https://zig.guide/0.12/standard-library/allocators Demonstrates using `create` and `destroy` for allocating and deallocating single items, as opposed to slices which use `alloc` and `free`. This is suitable for managing individual variables on the heap. ```zig const std = @import("std"); const expect = std.testing.expect; test "allocator create/destroy" { const byte = try std.heap.page_allocator.create(u8); defer std.heap.page_allocator.destroy(byte); byte.* = 128; } ``` -------------------------------- ### Generate and use random number in Zig Source: https://zig.guide/posts/a-guessing-game Demonstrates generating a random number within a range using Zig's PRNG. It initializes the PRNG with a seed and then uses it to get a random integer between 1 and 100. ```zig var prng: std.Random.DefaultPrng = .init(seed).(1625953); const rand = prng.random(); try stdout.print( "not-so random number: %\n", .{rand.intRangeAtMost(u8, 1, 100)}, ); ``` -------------------------------- ### Zig Page Allocator Example Source: https://zig.guide/0.12/standard-library/allocators Demonstrates the use of std.heap.page_allocator for allocating memory. It shows how to request memory and use `defer` with `free` for proper memory management, a common pattern in Zig. ```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); } ``` -------------------------------- ### Add Zig to Linux PATH Source: https://zig.guide/0.11/getting-started/installation This command appends the directory containing the Zig executable to the user's Bash configuration file, ensuring that the `zig` command can be run from any terminal location. It uses `echo` to write to `~/.bashrc`. ```shell echo 'export PATH="$HOME/zig-linux-x86_64-0.11.0:$PATH"' >> ~/.bashrc ``` -------------------------------- ### Zig Hello World Program Source: https://zig.guide/getting-started/hello-world A basic 'Hello World' program in Zig. It imports the standard library and prints 'Hello, World!' to stderr. Assumes UTF-8 encoding for the source file. ```zig const std = @import("std"); pub fn main() void { std.debug.print("Hello, {s}!\n", .{"World"}); } ``` -------------------------------- ### Extract Zig Archive on Linux Source: https://zig.guide/0.11/getting-started/installation This command extracts a compressed tar archive file, commonly used to unpack the downloaded Zig binary distribution on Linux systems. It requires the `tar` utility and the archive file name. ```shell tar xf zig-linux-x86_64-0.11.0.tar.xz ``` -------------------------------- ### Configure Zig Build Step for Documentation Generation Source: https://zig.guide/0.11/build-system/generating-documentation Shows how to set up a 'build.zig' file to generate documentation for a library. It defines a build step named 'docs' that utilizes the `emit_docs = .emit` setting. ```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); } ``` -------------------------------- ### Execute the 'run' step using Zig Build Source: https://zig.guide/0.12/build-system/zig-build This command shows how to execute the custom 'run' step defined in the Zig build system. It compiles the application and then runs the resulting executable. ```bash $ zig build run ``` -------------------------------- ### Zig ArrayList Example with Testing Allocator Source: https://zig.guide/standard-library/arraylist Demonstrates the basic usage of std.ArrayList in Zig, including appending individual elements and slices, and deinitializing the list. It utilizes the testing allocator to ensure memory is properly managed and to detect potential leaks during test execution. ```Zig const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; const ArrayList = std.ArrayList; const allocator = std.testing.allocator; test "arraylist" { var list: ArrayList(u8) = .empty; defer list.deinit(allocator); try list.append(allocator, 'H'); try list.append(allocator, 'e'); try list.append(allocator, 'l'); try list.append(allocator, 'l'); try list.append(allocator, 'o'); try list.appendSlice(allocator, " World!"); try expect(eql(u8, list.items, "Hello World!")); } ``` -------------------------------- ### Zig: Print Hello World to Standard Output Source: https://zig.guide/0.11/standard-library/formatting Illustrates printing a simple "Hello, World!" message to standard output using `std.io.getStdOut().writer().print`. This function writes formatted output directly to the console. ```zig const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; test "hello world" { const out_file = std.io.getStdOut(); try out_file.writer().print( "Hello, {s}!\n", .{"World"}, ); } ``` -------------------------------- ### Zig: Fill, Alignment, and Width in String Formatting Source: https://zig.guide/0.11/standard-library/advanced-formatting Illustrates how to use fill characters, alignment, and width specifiers in Zig string formatting. Examples show left, center, and right alignment with specified padding. ```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!", )); } ``` -------------------------------- ### Zig: Build Generic Data Structures using Structs and `comptime` Source: https://zig.guide/0.13/language-basics/comptime Demonstrates creating generic data structures in Zig using `struct` combined with `comptime` parameters. The `Vec` example defines a generic vector type that can hold arrays of any specified type and count, with methods like `init` and `abs`. Uses `std.mem.eql` and `std.testing.expect`. ```zig const expect = @import("std").testing.expect; fn Vec( comptime count: comptime_int, comptime T: type, ) type { return struct { data: [count]T, const Self = @This(); fn abs(self: Self) Self { var tmp = Self{ .data = undefined }; for (self.data, 0..) |elem, i| { tmp.data[i] = if (elem < 0) -elem else elem; } return tmp; } fn init(data: [count]T) Self { return Self{ .data = data }; } }; } const eql = @import("std").mem.eql; test "generic vector" { const x = Vec(3, f32).init([_]f32{ 10, -10, 5 }); const y = x.abs(); try expect(eql(f32, &y.data, &[_]f32{ 10, 10, 5 })); } ```