zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

commit 24f28753e6df3d0bea28afaccc02d0c9f50cd04f (tree)
parent 7cf6650663368a535ed7363721f2e3d49a2a6c92
Author: Gordon Cassie <gordoncassie@gmail.com>
Date:   Sat,  8 Jun 2024 12:39:11 -0700

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

Provide examples of various initializations.
Diffstat:
Mdoc/langref/test_basic_slices.zig | 10++++++++++
Mdoc/langref/test_multidimensional_arrays.zig | 4++++
Mdoc/langref/test_union_method.zig | 6++++--
3 files changed, 18 insertions(+), 2 deletions(-)

diff --git a/doc/langref/test_basic_slices.zig b/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 diff --git a/doc/langref/test_multidimensional_arrays.zig b/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 diff --git a/doc/langref/test_union_method.zig b/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