Commit 24f28753e6

Gordon Cassie <gordoncassie@gmail.com>
2024-06-08 21:39:11
Document a few non-obvious variable assignments (#20213)
Provide examples of various initializations.
1 parent 7cf6650
doc/langref/test_basic_slices.zig
@@ -42,6 +42,16 @@ test "basic slices" {
 
     // Note that `slice.ptr` does not invoke safety checking, while `&slice[0]`
     // asserts that the slice has len > 0.
+
+    // Empty slices can be created like this:
+    const empty1 = &[0]u8{};
+    // If the type is known you can use this short hand:
+    const empty2: []u8 = &.{};
+    try expect(empty1.len == 0);
+    try expect(empty2.len == 0);
+
+    // A zero-length initialization can always be used to create an empty slice, even if the slice is mutable.
+    // This is because the pointed-to data is zero bits long, so its immutability is irrelevant.
 }
 
 // test_safety=index out of bounds
doc/langref/test_multidimensional_arrays.zig
@@ -19,6 +19,10 @@ test "multidimensional arrays" {
             }
         }
     }
+
+    // initialize a multidimensional array to zeros
+    const all_zero: [4][4]f32 = .{.{0} ** 4} ** 4;
+    try expect(all_zero[0][0] == 0);
 }
 
 // test
doc/langref/test_union_method.zig
@@ -18,11 +18,13 @@ const Variant = union(enum) {
 };
 
 test "union method" {
-    var v1 = Variant{ .int = 1 };
-    var v2 = Variant{ .boolean = false };
+    var v1: Variant = .{ .int = 1 };
+    var v2: Variant = .{ .boolean = false };
+    var v3: Variant = .none;
 
     try expect(v1.truthy());
     try expect(!v2.truthy());
+    try expect(!v3.truthy());
 }
 
 // test