| 1 | const std = @import("std"); |
| 2 | const expectEqual = std.testing.expectEqual; |
| 3 | const expectEqualStrings = std.testing.expectEqualStrings; |
| 4 | const mem = std.mem; |
| 5 | |
| 6 | test "using slices for strings" { |
| 7 | // Zig has no concept of strings. String literals are const pointers |
| 8 | // to null-terminated arrays of u8, and by convention parameters |
| 9 | // that are "strings" are expected to be UTF-8 encoded slices of u8. |
| 10 | // Here we coerce *const [5:0]u8 and *const [6:0]u8 to []const u8 |
| 11 | const hello: []const u8 = "hello"; |
| 12 | const world: []const u8 = "世界"; |
| 13 | |
| 14 | var all_together: [100]u8 = undefined; |
| 15 | // You can use slice syntax with at least one runtime-known index on an |
| 16 | // array to convert an array into a slice. |
| 17 | var start: usize = 0; |
| 18 | _ = &start; |
| 19 | const all_together_slice = all_together[start..]; |
| 20 | // String concatenation example. |
| 21 | const hello_world = try mem.print(all_together_slice, "{s} {s}", .{ hello, world }); |
| 22 | |
| 23 | // Generally, you can use UTF-8 and not worry about whether something is a |
| 24 | // string. If you don't need to deal with individual characters, no need |
| 25 | // to decode. |
| 26 | try expectEqualStrings("hello 世界", hello_world); |
| 27 | } |
| 28 | |
| 29 | test "slice pointer" { |
| 30 | var array: [10]u8 = undefined; |
| 31 | const ptr = &array; |
| 32 | try expectEqual(*[10]u8, @TypeOf(ptr)); |
| 33 | |
| 34 | // A pointer to an array can be sliced just like an array: |
| 35 | var start: usize = 0; |
| 36 | var end: usize = 5; |
| 37 | _ = .{ &start, &end }; |
| 38 | const slice = ptr[start..end]; |
| 39 | // The slice is mutable because we sliced a mutable pointer. |
| 40 | try expectEqual([]u8, @TypeOf(slice)); |
| 41 | slice[2] = 3; |
| 42 | try expectEqual(3, array[2]); |
| 43 | |
| 44 | // Again, slicing with comptime-known indexes will produce another pointer |
| 45 | // to an array: |
| 46 | const ptr2 = slice[2..3]; |
| 47 | try expectEqual(1, ptr2.len); |
| 48 | try expectEqual(3, ptr2[0]); |
| 49 | try expectEqual(*[1]u8, @TypeOf(ptr2)); |
| 50 | } |
| 51 | |
| 52 | // test |