ArrayList
The
std.ArrayList
is commonly used throughout Zig, and serves as a buffer that can change in
size. std.ArrayList(T) is similar to C++'s std::vector<T> and Rust's
Vec<T>. The deinit() method frees all of the ArrayList's memory. The memory
can be read from and written to via its slice field - .items.
Here we will introduce the usage of the testing allocator. This is a special allocator that only works in tests and can detect memory leaks. In your code, use whatever allocator is appropriate.
const std = @import("std");
const expect = std.testing.expect;
const eql = std.mem.eql;
const ArrayList = std.ArrayList;
const test_allocator = std.testing.allocator;
test "arraylist" {
var list: ArrayList(u8) = .empty;
defer list.deinit(test_allocator);
try list.append(test_allocator, 'H');
try list.append(test_allocator, 'e');
try list.append(test_allocator, 'l');
try list.append(test_allocator, 'l');
try list.append(test_allocator, 'o');
try list.appendSlice(test_allocator, " World!");
try expect(eql(u8, list.items, "Hello World!"));
}
Coming from C++?▼
Coming from C++?
Zig's std.ArrayList is very comparable to C++'s std::vector.