master
1const std = @import("std");
2const expect = std.testing.expect;
3const mem = std.mem;
4const fmt = std.fmt;
5
6test "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 fmt.bufPrint(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 expect(mem.eql(u8, hello_world, "hello 世界"));
27}
28
29test "slice pointer" {
30 var array: [10]u8 = undefined;
31 const ptr = &array;
32 try expect(@TypeOf(ptr) == *[10]u8);
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 expect(@TypeOf(slice) == []u8);
41 slice[2] = 3;
42 try expect(array[2] == 3);
43
44 // Again, slicing with comptime-known indexes will produce another pointer
45 // to an array:
46 const ptr2 = slice[2..3];
47 try expect(ptr2.len == 1);
48 try expect(ptr2[0] == 3);
49 try expect(@TypeOf(ptr2) == *[1]u8);
50}
51
52// test