brain

tamnd's digital brain — notes, problems, research

42734 notes

Explicit Casts

Zig does not perform most numeric conversions automatically.

zigbook
Type Inference

A declaration may name its type explicitly.

zigbook
Start with the Rule

A collection is a type that stores many values.

zigbook
Important Builtins in Zig 1.16

This chapter covered the builtins you will see most often as a beginner.

zigbook
`@embedFile`

@embedFile reads a file at compile time and embeds its bytes into the final program.

zigbook
Characters and Bytes

Zig does not have a separate character type for ordinary strings.

zigbook
Booleans

A boolean value is either true or false.

zigbook
Floating-Point Types

Zig has floating-point types for numbers with fractional parts.

zigbook
Integer Types

Zig has signed and unsigned integer types.

zigbook
`const` and `var`

Zig has two kinds of variable declarations:

zigbook
Names and Declarations

A Zig program is made from declarations.

zigbook
Exercises

The programs in this chapter are small. They are meant to be changed, broken, rebuilt, and studied.

zigbook
A Word-Count Program

A useful program reads text and counts something.

zigbook
Reading Command-Line Arguments

Programs often need input.

zigbook
A Small Calculator

A program can compute a value before it prints it.

zigbook
Printing Values

The function std.debug.print writes text.

zigbook
Variables and Constants

A program works with values. In Zig, values are usually stored in constants or variables.

zigbook
Build and Run

There are two common ways to run a small Zig program.

zigbook
Hello, Zig

The first program in Zig is small.

zigbook
Hello, Zig

The first program in Zig is small.

zigbook
`@compileError`

@compileError stops compilation with a custom error message.

zigbook
`@panic`

@panic stops the program immediately with a message.

zigbook
Appendix I. Zig Coding Style Guide

Zig code should be explicit, simple, and easy to inspect. The goal is not cleverness. The goal is code that another programmer can read, verify, and maintain.

zigbook
Contributing to Zig

Contributing to Zig means helping the language, compiler, standard library, documentation, tests, or tooling improve.

zigbook
Build a Programming Language Lexer

A lexer is the first stage of many programming language tools.

zigbook
Handling Platform Differences

A cross-platform Zig program should not pretend that every operating system behaves the same way. Windows, Linux, macOS, WebAssembly, and embedded targets have different...

zigbook
Writing a Compiler in Zig

A compiler translates one form of code into another form.

zigbook
Benchmark the Right Thing

Benchmarking means measuring how fast code runs.

zigbook
Writing a TCP Server

A TCP server is a program that waits for clients to connect.

zigbook
Event Loops

An event loop is code that waits for events, then runs the right piece of work for each event.

zigbook
ABI Compatibility

ABI means Application Binary Interface.

zigbook
Memory Debugging

Memory debugging means finding mistakes in how a program uses memory.

zigbook
Running Tests

Zig has built-in support for tests.

zigbook
Time and Timers

Programs often need to work with time.

zigbook
`@floatCast`

@floatCast converts one floating-point value to another floating-point type.

zigbook
Appendix H. Useful Open Source Zig Projects

This appendix lists useful Zig projects to read after you know the basics.

zigbook
Open Issues and RFCs

A programming language is never only its syntax.

zigbook
Build a Small Database

A database stores data so it can be saved, searched, updated, and loaded again later.

zigbook
Portable APIs

A portable API is an interface that works across more than one platform.

zigbook
Writing a Virtual Machine

A virtual machine is a program that runs another program.

zigbook
Why Branch Prediction Exists

Branch prediction is a CPU optimization.

zigbook
Network Protocols

A network protocol is a rulebook for how programs talk over a network.

zigbook
Await and Suspension

await means: wait until an asynchronous operation has finished, then continue with its result.

zigbook
Exporting Zig to C

Zig can call C, but C can also call Zig.

zigbook
Using GDB and LLDB

GDB and LLDB are debuggers.

zigbook
Release Modes

Zig can build the same program in different optimization modes.

zigbook
Parsing Numbers and Text

Parsing means turning text into data.

zigbook
Why Trees Matter

A tree is a collection made of nodes.

zigbook
Building Allocation-Friendly APIs

An allocation-friendly API makes memory behavior clear to the caller.

zigbook
`@truncate`

@truncate converts an integer to a smaller integer type by keeping only the low bits.

zigbook
Appendix G. C Interop Reference

Zig is designed to work closely with C. You can call C from Zig, call Zig from C, compile C code with Zig, and link Zig programs against existing C libraries.

zigbook
LLVM Integration

LLVM is a compiler infrastructure project.

zigbook
Build a Memory Allocator

A memory allocator is code that gives memory to the rest of a program.

zigbook
Cross-Target Debugging

Cross-target debugging means debugging a program built for a different machine, operating system, or CPU architecture than the one you are sitting at.

zigbook
Writing a Parser

A parser reads text and turns it into structure.

zigbook
Small Values Are Fine to Copy

Copying data is sometimes necessary, but unnecessary copying is one of the easiest ways to waste time and memory.

zigbook
Endianness

Endianness means the order used to store the bytes of a multi-byte value.

zigbook
Async Functions

Async code lets a program start an operation now and receive the result later.

zigbook
Building Mixed Zig and C Projects

A mixed Zig and C project contains source files from both languages.

zigbook
Assertions

An assertion is a check that must be true while the program runs.

zigbook
Static and Dynamic Linking

Linking is the step where the compiler connects your program with the code it depends on.

zigbook
Formatting and Printing

Formatting means turning values into text.

zigbook
The Core Idea

A ring buffer is a fixed-size queue that reuses its storage.

zigbook
Lifetime Management

Memory lifetime means:

zigbook
`@intCast`

@intCast converts one integer value to another integer type.

zigbook
When Not to Use `comptime`

comptime is one of Zig’s strongest features, but it should not be used everywhere.

zigbook
Appendix F. Build Modes Reference

When Zig compiles a program, it can build the program in different modes.

zigbook
Code Generation

Code generation is the compiler stage that turns analyzed program meaning into target code.

zigbook
Build a Thread Pool

A thread pool is a group of worker threads that wait for jobs.

zigbook
ARM and Embedded Targets

ARM is a CPU architecture family used in phones, tablets, laptops, routers, Raspberry Pi boards, microcontrollers, servers, and many embedded devices. When you write Zig for...

zigbook
Writing a Game Engine Core

A game engine core is the small central layer that runs the game.

zigbook
Why Allocations Cost Time

Allocations are one of the most common causes of slow programs.

zigbook
Binary File Formats

A binary file format stores data as bytes with a specific structure.

zigbook
Condition Variables

A condition variable lets one thread sleep until another thread says that something has changed.

zigbook
Linking C Libraries

Importing a C header lets Zig understand a C API. Linking gives the final program the actual compiled code.

zigbook
Stack Traces

A stack trace shows how your program reached a failure.

zigbook
Cross Compilation

Cross compilation means building a program for a different machine than the one you are using.

zigbook
Directories and Paths

A file lives inside a directory.

zigbook
Why Bit Sets Matter

A bit set is a compact collection of yes-or-no values.

zigbook
Memory Leak Detection

A memory leak happens when a program allocates memory and then loses the ability to free it.

zigbook
`@memcpy`

@memcpy copies bytes from one memory region to another.

zigbook
Metaprogramming Patterns

Metaprogramming means writing code that helps create, inspect, or specialize other code.

zigbook
Volatile and Atomic Memory

Most memory in Zig is ordinary memory.

zigbook
LeetCode 1071: Greatest Common Divisor of Strings

A clear explanation of finding the longest string that divides both strings using the GCD of their lengths.

leetcodemathstring
LeetCode 1039: Minimum Score Triangulation of Polygon

A clear explanation of minimizing the total score of triangulating a polygon using interval dynamic programming.

leetcodearraydynamic-programming
LeetCode 1058: Minimize Rounding Error to Meet Target

A clear explanation of minimizing total rounding error when rounding prices to meet a target sum using a greedy approach.

leetcodearraymathgreedysorting
LeetCode 1036: Escape a Large Maze

A clear explanation of determining if a source can reach a target in a very large grid with blocked cells using BFS with a cell count limit.

leetcodearrayhash-tablebreadth-first-search
LeetCode 1020: Number of Enclaves

A clear explanation of counting land cells unreachable from the grid border using BFS from boundary land cells.

leetcodearraydepth-first-searchbreadth-first-searchunion-findmatrix
LeetCode 1069: Product Sales Analysis II

A clear explanation of computing total quantity sold per product using GROUP BY and SUM aggregation.

leetcodedatabase
LeetCode 1077: Project Employees III

A clear explanation of finding the most experienced employee(s) for each project using a window function or correlated subquery.

leetcodedatabase
LeetCode 1094: Car Pooling

A clear explanation of determining if a car can transport all passengers using a difference array for passenger count tracking.

leetcodearraysortingheapsimulationprefix-sum
LeetCode 1031: Maximum Sum of Two Non-Overlapping Subarrays

A clear explanation of finding two non-overlapping subarrays with maximum combined sum using prefix sums and running maximums.

leetcodearraydynamic-programmingsliding-windowprefix-sum
LeetCode 1006: Clumsy Factorial

A clear explanation of computing the clumsy factorial by simulating cyclic operators with a stack.

leetcodemathstacksimulation
LeetCode 1003: Check If Word Is Valid After Substitutions

A clear explanation of validating a string by repeatedly removing 'abc' substrings using a stack.

leetcodestringstack
LeetCode 1029: Two City Scheduling

A clear explanation of minimizing total travel cost for two-city scheduling using a greedy refund approach after sending everyone to city A.

leetcodearraygreedysorting
LeetCode 1080: Insufficient Nodes in Root to Leaf Paths

A clear explanation of pruning tree nodes where all root-to-leaf paths through them have sum less than a limit, using post-order DFS.

leetcodetreedepth-first-searchbinary-tree
LeetCode 1078: Occurrences After Bigram

A clear explanation of finding all words that follow a two-word sequence in a text string.

leetcodestring
LeetCode 1067: Digit Count in Range

A clear explanation of counting the occurrences of a specific digit in all numbers from 1 to n using digit dynamic programming.

leetcodemathdynamic-programming
LeetCode 1100: Find K-Length Substrings With No Repeated Characters

A clear explanation of counting substrings of length k with all unique characters using a sliding window.

leetcodehash-tablestringsliding-window
LeetCode 1044: Longest Duplicate Substring

A clear explanation of finding the longest duplicate substring using binary search on length combined with Rabin-Karp rolling hash.

leetcodestringbinary-searchsliding-windowrolling-hashsuffix-array