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

Provide examples of various initializations.
This commit is contained in:
Gordon Cassie 2024-06-08 12:39:11 -07:00 committed by GitHub
parent 7cf6650663
commit 24f28753e6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 18 additions and 2 deletions

View File

@ -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

View File

@ -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

View File

@ -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