Learning Zig from the official language reference.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
zig-langref/arrays.zig

114 lines
2.4 KiB

const std = @import("std");
const debug = std.debug;
const mem = std.mem;
const testing = std.testing;
const message = [_]u8{ 'h', 'e', 'l', 'l', 'o' };
comptime {
testing.expect(message.len == 5);
}
const same_message = "hello";
comptime {
testing.expect(mem.eql(u8, &message, same_message));
}
test "iterate over an array" {
for (message) |c| {
debug.print("{c}\n", .{c});
}
// the same without the encoding hint
for (message) |c| {
debug.print("{}\n", .{c});
}
var sum: usize = 0;
for (message) |b| {
sum += b;
}
debug.print("{}\n", .{sum});
}
var some_integers: [100]i32 = undefined;
test "modify an array" {
for (some_integers) |*item, idx| {
item.* = @intCast(i32, idx);
}
testing.expect(some_integers[0] == 0);
testing.expect(some_integers[10] == 10);
}
const hello = "hello";
const world = ", world";
const hello_world = hello ++ world;
comptime {
testing.expect(mem.eql(u8, hello_world, &[_]u8{ 'h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd' }));
}
const pattern = "abc" ** 3;
comptime {
testing.expect(mem.eql(u8, pattern, "abcabcabc"));
}
const all_zero = [_]u16{0} ** 10;
comptime {
testing.expect(all_zero.len == 10);
testing.expect(all_zero[5] == 0);
}
// comptime initialisation of an array
const Point = struct {
x: i32,
y: i32,
pub fn eq(self: Point, other: *const Point) bool {
return self.x == other.x and self.y == other.y;
}
};
var fancy_array = init: {
var initial_value: [10]Point = undefined;
for (initial_value) |*pt, idx| {
pt.* = Point{
.x = @intCast(i32, idx),
.y = @intCast(i32, idx) * 2,
};
}
break :init initial_value;
};
test "fancy array" {
testing.expect(fancy_array.len == 10);
testing.expect(fancy_array[2].eq(&Point{ .x = 2, .y = 4 }));
testing.expect(fancy_array[3].eq(&fancy_array[3]));
}
// call a function to initialise an array
// if this were var instead of const, then this would not work - the
// Zig compiler is not smart enough yet.
const more_points = [_]Point{makePoint(1, 2)} ** 10;
fn makePoint(x: i32, y: i32) Point {
return Point{
.x = x,
.y = y,
};
}
comptime {
testing.expect(more_points.len == 10);
testing.expect(more_points[1].x == 1);
testing.expect(more_points[1].y == 2);
}