38 lines
1.9 KiB
Zig
38 lines
1.9 KiB
Zig
const std = @import("std");
|
|
const expect = std.testing.expect;
|
|
// 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 `std.ArrayList`'s memory.
|
|
// The memory can be read from and written to via its slice field - `.items`.
|
|
// `std.ArrayList` 는 Zig 에서 많이 사용되는 버퍼로, 크기를 변경할 수 있는 버퍼를 제공합니다.
|
|
// `std.ArrayList(T)` 는 C++의 `std::vector<T>` 와 Rust의 `Vec<T>` 와 유사합니다.
|
|
// `deinit()` 메서드는 `std.ArrayList`의 모든 메모리를 해제합니다.
|
|
// 메모리는 `.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.
|
|
// 여기서는 테스트 할당자(testing allocator)의 사용법을 소개합니다.
|
|
// 이 할당자는 테스트에서만 동작하며 메모리 누수를 감지할 수 있는 특별한 할당자입니다.
|
|
// 실제 코드에서는 상황에 맞는 할당자를 사용하면 됩니다.
|
|
const eql = std.mem.eql;
|
|
const ArrayList = std.ArrayList;
|
|
const allocator = std.testing.allocator;
|
|
|
|
test "arraylist" {
|
|
var list: ArrayList(u8) = .empty;
|
|
defer list.deinit(allocator);
|
|
try list.append(allocator, 'H');
|
|
try list.append(allocator, 'e');
|
|
try list.append(allocator, 'l');
|
|
try list.append(allocator, 'l');
|
|
try list.append(allocator, 'o');
|
|
try list.appendSlice(allocator, " World!");
|
|
|
|
try expect(eql(u8, list.items, "Hello World!"));
|
|
}
|
|
|
|
// Coming from C++?
|
|
// Zig's std.ArrayList is very comparable to C++'s std::vector.
|
|
// Zig의 std.ArrayList는 C++의 std::vector와 매우 비슷합니다.
|