Chuyển đến nội dung

Bài 9 · Language Basics

Arrays and Slices

Learn Zig arrays and slices: [N]T fixed-size arrays, [_] inference, indexing and bounds checks, slicing with ranges, []const T, multidimensional arrays and sentinel-terminated arrays.

Zig has two fundamental ways to hold a sequence of values. An array has its length baked into its type and lives wherever you put it. A slice is a view into some elements: a pointer plus a length. Almost every function that works on sequences takes a slice, and understanding the pair removes most of C's pointer-and-length bookkeeping.

Arrays

An array type is written [N]T: N elements of type T. N must be known at compile time.

ZIG
const std = @import("std");

pub fn main() void {
    const primes = [5]u32{ 2, 3, 5, 7, 11 };
    const letters = [_]u8{ 'a', 'b', 'c' };   // [_] lets the compiler count: [3]u8
    var grid: [4]i32 = [_]i32{0} ** 4;        // four zeros

    grid[2] = 9;

    std.debug.print("{d} primes, first {d}, last {d}\n", .{ primes.len, primes[0], primes[primes.len - 1] });
    std.debug.print("{d} letters, grid[2] = {d}\n", .{ letters.len, grid[2] });
}
TEXT
5 primes, first 2, last 11
3 letters, grid[2] = 9

Key facts:

  • array.len is a compile-time constant for arrays.
  • Indexes are usize (or compile-time numbers). An out-of-bounds index is a compile error when it is known at compile time, and a panic in safe builds when only known at runtime.
  • Arrays are values: assigning one array to another copies every element.
  • A const array is immutable; use var to change elements.

Arrays can be left uninitialized with undefined, which is common for buffers:

ZIG
var buffer: [256]u8 = undefined;

Multidimensional arrays

An array of arrays is a grid:

ZIG
var board: [3][3]u8 = [_][3]u8{[_]u8{'.'} ** 3} ** 3;
board[1][1] = 'X';

board.len is 3 (rows) and board[0].len is 3 (columns). Memory is row-major, as in C.

Slices

A slice type is written []T (mutable elements) or []const T (read-only). It holds a pointer and a length, two machine words, and can refer to any run of elements in an array, in heap memory, or in a string literal.

ZIG
const std = @import("std");

fn sum(values: []const u32) u32 {
    var total: u32 = 0;
    for (values) |v| total += v;
    return total;
}

pub fn main() void {
    const numbers = [_]u32{ 10, 20, 30, 40, 50 };

    const all: []const u32 = &numbers;        // slice of the whole array
    const middle = numbers[1..4];             // elements 1, 2, 3
    const tail = numbers[3..];                // from index 3 to the end

    std.debug.print("{d} {d} {d}\n", .{ sum(all), sum(middle), sum(tail) });
    std.debug.print("middle len = {d}, first = {d}\n", .{ middle.len, middle[0] });
}
TEXT
150 90 90
middle len = 3, first = 20

The range a..b includes a and excludes b. numbers[1..4] has length 3. Omit the end to go to the end (numbers[3..]); the start is always written, so a prefix is numbers[0..2]. Slicing is checked: a range past the end panics in safe modes.

Array versus slice

[N]T array Length is part of the type; owns its elements
[]T slice Pointer and length; a view of elements stored elsewhere
a[1..4] Start included, end excluded

Functions take slices so they work with any array size.

1 / 2

Mutable slices

A []T slice allows writing through it, and the writes reach the original storage:

ZIG
var data = [_]i32{ 1, 2, 3, 4, 5 };
const window = data[1..4];     // []i32 because data is var
window[0] = 20;
window[2] = 40;
// data is now { 1, 20, 3, 40, 5 }

A slice never owns memory. If the array goes out of scope while a slice still points into it, you have a dangling slice, the same class of bug as a dangling pointer in C. Zig cannot prevent this for you in general, so be careful about returning slices of local arrays.

Array pointers

Taking the address of an array gives a pointer to the array, *[5]u32, which coerces to a slice []u32 automatically. It still remembers its length at compile time, which is why you can write &numbers where a slice is expected.

Looping and common operations

ZIG
for (numbers, 0..) |value, index| { ... }   // value and index
for (numbers[1..]) |value| { ... }          // skip the first

const std = @import("std");
const found = std.mem.indexOfScalar(u32, &numbers, 30);   // ?usize
std.mem.reverse(u32, &mutable_array);
std.mem.sort(u32, &mutable_array, {}, std.sort.asc(u32));
@memcpy(dest[0..3], src[0..3]);                // copy equal-length slices
@memset(&buffer, 0);                           // fill with a value

@memcpy requires the two slices to have the same length and not overlap. Use std.mem.copyForwards or copyBackwards for overlapping regions.

Sentinel-terminated arrays

Strings from C end with a zero byte. Zig models this in the type: [N:0]u8 is an array of N elements followed by a hidden zero, and [:0]const u8 is a slice with a known zero after the end. String literals have this type, which is why you can pass them straight to C functions. Sentinel types are covered in the strings lesson.

Stand-ins you can run

A slice is nothing more than a pointer and a length. This C stand-in builds one explicitly, which is exactly what Zig does for you in numbers[1..4].

C Stand-in (C): a slice is pointer plus length

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Rust has the same idea built in, with the same half-open ranges:

Rust Stand-in (Rust): slices and ranges

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What is the type of [_]u8{ 1, 2, 3 }?

    [_] asks the compiler to count the elements, giving [3]u8.
  2. 2. What does numbers[1..4] contain for {10,20,30,40,50}?

    The start index is included and the end index is excluded.
  3. 3. What is a slice at runtime?

    Slices are views; they hold a pointer and a length and own nothing.
  4. 4. What happens on an out-of-bounds runtime index in a Debug build?

    Bounds checks are part of Zig's runtime safety in Debug and ReleaseSafe.
  5. 5. Which type does a function usually take to accept arrays of any size?

    A slice parameter accepts a pointer to any array, or any other run of elements.

Summary

  • [N]T arrays store their length in the type, copy by value, and are indexed with usize.
  • []T and []const T slices are a pointer plus a length; a[start..end] excludes end.
  • Bounds are checked at compile time when possible and at runtime in safe builds.
  • Slices own nothing, so never keep one after its storage is gone.
  • Use [_]T{...} to let the compiler count, and ** to repeat values.

Next: Strings and Characters

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.