I loved Java Puzzlers and whenever I encounter some unexpected behaviour, I turn it into a puzzler for others to enjoy.
Here is a "fill in the blank" Zig puzzler:
const std = @import("std");
test {
// YOUR CODE HERE
try std.testing.expectEqual(0, slice.len);
try std.testing.expectEqual(42, slice[0]);
}
All you need to do is make the test pass. But Zig is zero indexed. How can the slice both have zero length AND the first element is 42???
Pause here if you want to take a stab at this puzzler.
Hints will be after the cat picture.
Hint 1. There is no undefined behaviour memory trickery here. It is plain normal valid Zig.
Hint 2. There is nothing tricky going on with std
.
Hint 3. slice
is indeed a slice.
The solution will be after the cat picture.
Solution: The slice is sentinel terminated.
const slice: [:42]const u8 = &[_:42]u8{};
Sentinel terminated slices don't include the sentinel as part of .len
. In memory, slice
is 1 byte long, with the value 42
.
An alternative solution is to use an array.
const slice: [0:42]u8 = undefined;
Latest comments (4)
beautiful
love it!
Love this idea of puzzles for a post ππΌ thanks for sharing ππΌ
nice one :)