authorgravatar for gordoncassie@gmail.comGordon Cassie <gordoncassie@gmail.com> 2024-06-08 12:39:11-07:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2024-06-08 12:39:11-07:00
log24f28753e6df3d0bea28afaccc02d0c9f50cd04f
treeca8d52351ff8ca58c4c71fb9a842fb9d80c95c75
parent7cf6650663368a535ed7363721f2e3d49a2a6c92
signaturebadge-check Signed by PGP key B5690EEEBB952194

Document a few non-obvious variable assignments (#20213)

Provide examples of various initializations.

3 files changed, 18 insertions(+), 2 deletions(-)

doc/langref/test_basic_slices.zig+10
...@@ -42,6 +42,16 @@ test "basic slices" {...@@ -42,6 +42,16 @@ test "basic slices" {
4242
43 // Note that `slice.ptr` does not invoke safety checking, while `&slice[0]`43 // Note that `slice.ptr` does not invoke safety checking, while `&slice[0]`
44 // asserts that the slice has len > 0.44 // asserts that the slice has len > 0.
45
46 // Empty slices can be created like this:
47 const empty1 = &[0]u8{};
48 // If the type is known you can use this short hand:
49 const empty2: []u8 = &.{};
50 try expect(empty1.len == 0);
51 try expect(empty2.len == 0);
52
53 // A zero-length initialization can always be used to create an empty slice, even if the slice is mutable.
54 // This is because the pointed-to data is zero bits long, so its immutability is irrelevant.
45}55}
4656
47// test_safety=index out of bounds57// test_safety=index out of bounds
doc/langref/test_multidimensional_arrays.zig+4
...@@ -19,6 +19,10 @@ test "multidimensional arrays" {...@@ -19,6 +19,10 @@ test "multidimensional arrays" {
19 }19 }
20 }20 }
21 }21 }
22
23 // initialize a multidimensional array to zeros
24 const all_zero: [4][4]f32 = .{.{0} ** 4} ** 4;
25 try expect(all_zero[0][0] == 0);
22}26}
2327
24// test28// test
doc/langref/test_union_method.zig+4-2
...@@ -18,11 +18,13 @@ const Variant = union(enum) {...@@ -18,11 +18,13 @@ const Variant = union(enum) {
18};18};
1919
20test "union method" {20test "union method" {
21 var v1 = Variant{ .int = 1 };21 var v1: Variant = .{ .int = 1 };
22 var v2 = Variant{ .boolean = false };22 var v2: Variant = .{ .boolean = false };
23 var v3: Variant = .none;
2324
24 try expect(v1.truthy());25 try expect(v1.truthy());
25 try expect(!v2.truthy());26 try expect(!v2.truthy());
27 try expect(!v3.truthy());
26}28}
2729
28// test30// test