Array Basics ([N]T)
In Zig, arrays are fixed-length data structures. The type is written as [N]T, where N is the number of elements and T is the element type. Because the length is determined at compile time, arrays are efficiently allocated on the stack. This page covers how to declare fixed-length arrays, access their elements, and initialize them.
Syntax
// -----------------------------------------------
// Declaring and initializing a fixed-length array
// -----------------------------------------------
// Initialize using a [N]T type literal
// N: number of elements (compile-time constant)
// T: element type
const arr: [N]T = [N]T{ value1, value2, ... };
// The element count can be omitted with _ (inferred from the literal)
const arr = [_]T{ value1, value2, ... };
// -----------------------------------------------
// Accessing elements
// -----------------------------------------------
arr[index] // Retrieves the element at the given 0-based index
arr[index] = value; // Assignment is only allowed for var declarations (not const)
// -----------------------------------------------
// Getting the array length
// -----------------------------------------------
arr.len // Returns the number of elements in the array (type: usize)
// -----------------------------------------------
// Zero initialization
// -----------------------------------------------
var arr = [_]T{ 0 } ** N; // Initializes all elements to 0 (** is the repetition operator)
Syntax Reference
| Syntax / Method | Description |
|---|---|
[N]T{ ... } | Defines a fixed-length array literal with N elements of type T. |
[_]T{ ... } | Defines a fixed-length array, inferring the element count from the literal. |
arr[i] | Retrieves the element at index i. Indices are 0-based. |
arr[i] = value | Assigns a value to index i of a var-declared array. |
arr.len | Returns the number of elements in the array as type usize. |
value ** N | Produces an array by repeating a value or single-element array N times. |
arr[start..end] | Creates a slice covering indices from start up to (but not including) end. |
arr[0..] | Creates a slice covering the entire array. |
Sample Code
psychopass_array.zig
// psychopass_array.zig — demonstrates array declaration, access, and initialization
// Uses PSYCHO-PASS characters to explore
// basic operations on [N]T arrays
// Import the standard library
const std = @import("std");
pub fn main() !void {
// Get a writer for standard output
const stdout = std.io.getStdOut().writer();
// -----------------------------------------------
// 1. Declaring and initializing a const array
// -----------------------------------------------
// Using [_] lets the compiler infer the element count (5 in this case)
const inspectors = [_][]const u8{
"Tsunemori Akane", // index 0
"Ginoza Nobuchika", // index 1
"Kogami Shinya", // index 2
"Masaoka Tomomi", // index 3
"Karanomori Shion", // index 4
};
try stdout.print("=== PSYCHO-PASS Inspectors & Enforcers ===\n\n", .{});
// Use the .len property to get the element count
try stdout.print("Registered: {d}\n\n", .{inspectors.len});
// Access individual elements by index
try stdout.print("Inspector: {s}\n", .{inspectors[0]});
try stdout.print("Enforcer (former inspector): {s}\n\n", .{inspectors[2]});
// -----------------------------------------------
// 2. Iterating over all elements with a for loop
// -----------------------------------------------
try stdout.print("--- All members ---\n", .{});
for (inspectors, 0..) |name, i| {
// {d} formats an integer as decimal; {s} formats a string
try stdout.print(" [{d}] {s}\n", .{ i, name });
}
try stdout.print("\n", .{});
// -----------------------------------------------
// 3. Assigning values to a var array
// -----------------------------------------------
// Create a zero-initialized array using the ** operator
// Stores crime coefficients (range: 0–299)
var crime_coefficients = [_]u16{0} ** 5;
// Assign values to each index (allowed because of var declaration)
crime_coefficients[0] = 28; // Tsunemori Akane
crime_coefficients[1] = 42; // Ginoza Nobuchika
crime_coefficients[2] = 136; // Kogami Shinya
crime_coefficients[3] = 98; // Masaoka Tomomi
crime_coefficients[4] = 55; // Karanomori Shion
try stdout.print("--- Crime Coefficients ---\n", .{});
for (inspectors, crime_coefficients) |name, coeff| {
try stdout.print(" {s}: {d}\n", .{ name, coeff });
}
try stdout.print("\n", .{});
// -----------------------------------------------
// 4. Accessing a sub-range with a slice
// -----------------------------------------------
// arr[start..end] references elements from start (inclusive) to end (exclusive)
const field_team = inspectors[0..2]; // Tsunemori Akane & Ginoza Nobuchika
try stdout.print("--- Field team (first 2 members) ---\n", .{});
for (field_team) |name| {
try stdout.print(" {s}\n", .{name});
}
}
zig run psychopass_array.zig === PSYCHO-PASS Inspectors & Enforcers === Registered: 5 Inspector: Tsunemori Akane Enforcer (former inspector): Kogami Shinya --- All members --- [0] Tsunemori Akane [1] Ginoza Nobuchika [2] Kogami Shinya [3] Masaoka Tomomi [4] Karanomori Shion --- Crime Coefficients --- Tsunemori Akane: 28 Ginoza Nobuchika: 42 Kogami Shinya: 136 Masaoka Tomomi: 98 Karanomori Shion: 55 --- Field team (first 2 members) --- Tsunemori Akane Ginoza Nobuchika
Overview
Fixed-length arrays in Zig are represented by the [N]T type, where N is a compile-time constant element count and T is the element type. When initializing with an array literal, you can write [_]T instead of specifying N explicitly, and the compiler will infer the count automatically. Elements are accessed with arr[i] (0-based), and the element count is available via arr.len. Arrays declared with const cannot have their elements reassigned, but var-declared arrays allow arr[i] = value. For zero initialization, [_]T{0} ** N using the repetition operator ** is a convenient approach. To reference a subset of elements, use arr[start..end] to create a slice. If you need a variable-length collection, see ArrayList (dynamic array); for multi-dimensional arrays, see Multidimensional Arrays.
If you find any errors or copyright issues, please contact us.