3 ms·
> If I were to use indices out of range, presumably that would that give me a compile time error? yup $ zig test test.zig test.zig:8:56: error: index
by llimllib 3y ago
> If I were to use indices out of range, presumably that would that give me a compile time error?
yup
$ zig test test.zig
test.zig:8:56: error: index 3 outside array of length 2
std.debug.print("\ncompile error: {d}\n", .{slice2[3]});
> Could I use variables as the indices and, if so, could I get a seg fault at runtime or are there some sort of guards on there?
Bounds are checked by default:
$ zig test test.zig
test.zig:9:56: error: index 3 outside array of length 2
std.debug.print("\ncompile error: {d}\n", .{slice2[invalid_index]});
But you can disable them by building in `ReleaseFast` mode[1]
Here's a test file you can use to play around with it if you like:
const std = @import("std");
test "bounds" {
var arr = [_]u32{ 1, 2, 3, 4, 5, 6 }; // 1, 2, 3, 4, 5, 6
const slice1 = arr[1..5]; // 2, 3, 4, 5
const slice2 = slice1[1..3]; // 3, 4
const invalid_index: usize = 3;
std.debug.print("\nslice2: {d} {d}\n", .{ slice2[0], slice2[1] });
std.debug.print("\ncompile error: {d}\n", .{slice2[invalid_index]});
try std.testing.expect(slice2.len == 2);
}
1: https://ziglang.org/documentation/master/#Build-Mode https://ziglang.org/documentation/master/#Build-Mode