Open-Source Zig Programming • Beginner to intermediate • Estimated study time: 45 minutes
Fixed-size arrays and slices organize contiguous memory without requiring a dynamically growing collection. An embedded application might keep a fixed buffer of sensor readings while handing only a selected region to a processing function. Continue from OSZig.004 on loops and ranges. All data in the exercises are fictional. The Zig 0.17.1 language reference is the primary syntax reference.
Prerequisites, materials and learning objectives
Use a local computer, UTF-8 text editor, terminal and Zig 0.17.1 toolchain. Review OSZig.002 on variables and mutability. No physical equipment or production access is required. Work in an isolated training directory.
- Declare fixed-length arrays and explain value-copy behavior.
- Pass a mutable slice and demonstrate changes to its backing storage.
- Use read-only slices to accept different array lengths.
- Reject invalid indices and handle empty slices.
- Explain the difference between a slice, its backing storage and its lifetime.
Arrays have a compile-time length
An array type such as [4]u16 includes the number of elements as part of its type. The inferred-length notation [_]u16 lets the compiler count initializer elements. Array indexing starts at zero; the final valid index is one less than the length. Assigning an array value to another array variable copies its elements. Mutating the copy does not change the source. The following test demonstrates independent values:
The expected original second value remains 20 while the copied second value becomes 99. Both arrays have four elements. In contrast, a slice does not copy the underlying element sequence.
Slices share contiguous backing memory
A slice carries an element pointer and length. A half-open range [start..end] includes the starting index and excludes the ending index. In a fixed array, compile-time-known bounds can infer a pointer-to-array type rather than a slice. An explicit []u16 destination requests a mutable slice through coercion. A constant slice binding can still permit changes to mutable elements. The following function increments only the selected region:
The expected backing values become 10, 21, 31 and 40. The first and fourth elements remain unchanged. A slice is a borrowed view; it neither allocates storage nor automatically extends the lifetime of the memory it references. Do not return a slice to a local array whose lifetime ends when the function returns. Keep backing memory valid for every use, and never use a view after its allocation has been freed.
Read-only access and explicit index validation
A parameter declared []const u16 prevents mutation through that view, even when the underlying array belongs to a mutable caller. Read-only access does not guarantee global immutability if another mutable alias exists. A slice has a length but no inherent ownership or resizing capacity. An ordinary slice cannot be indexed at its length, and an empty slice cannot be indexed at zero. Runtime bounds checking is generally enabled in Debug and ReleaseSafe builds, but release modes without safety checks must not be relied upon to reject invalid inputs. Review OSZig.003 on optional values before implementing a checked lookup. The following helper explicitly returns absence rather than accessing an invalid index:
A valid index returns an optional containing a value. Index three in a three-element input returns null. The empty input also returns null. Validate both range endpoints before slicing externally supplied offsets: require start ≤ end ≤ length. Avoid converting unchecked signed offsets to unsigned indices.
A single function handles different lengths
Using a read-only slice lets the same function consume multiple array sizes without encoding the array length into its signature. Widening the accumulator from u16 to u64 prevents overflow for the small examples, though a production algorithm must still establish a bound or explicitly handle overflow. Compare OSGo.006 on Go arrays and slices for the distinction between languages: Zig slices do not provide Go’s capacity or append behavior. The following tests demonstrate reuse across differently sized arrays and empty ranges:
Practical lab and assessment
Copy the four examples in order into one file named slices.zig, keeping the initial import once. Run the following commands locally:
The expected result is four passing tests. Compare the actual compiler output with the expected assertions; report any compiler mismatch rather than treating the predicted result as an executed test.
- Change the second element of the copied array to 50. What value remains in source[1]?
- Select readings[0..2] in the mutation test. Which elements change?
- What does get(&values, 2) return, and what does get(&values, 3) return?
- What is the length of readings[2..2]? Can its index zero be read?
- Why must a slice returned from a function not reference expired local storage?
Answer key and troubleshooting
- 20; modifying the copied array does not modify the original.
- The first two elements become 11 and 21; the remaining values are 30 and 40. Update the test assertions accordingly.
- The first lookup contains 9; the second returns null.
- Zero; there is no valid element index.
- A view does not own its backing storage or extend its lifetime. Access to expired storage is invalid.
If a compiler rejects mutation, inspect whether the destination type is read-only and whether the source storage is mutable. If an index fails, verify the half-open range, the slice length and whether the supplied position is relative to the slice rather than the original array. The official slice reference provides further examples.
Technical verification: examples were reviewed against the versioned language reference. The editorial environment did not have a Zig compiler, so the expected test outcomes are not reported as executed results.
We volunteer daily to ensure the credibility of the information on the platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiative, please scan the QR code below.


Leave a Reply