From 4c5394b367562ccca37f66ef64cb2b3978c0c283 Mon Sep 17 00:00:00 2001
From: Andrew Kelley
TODO consider suggesting std.MultiArrayList
Vectors and {#link|Arrays#} each have a well-defined bit layout @@ -2150,6 +2150,24 @@ or {#see_also|Pointers|for|Arrays#} + {#header_open|Slicing by Length#} +
Even though Zig only has syntax for slicing based on start and end indices, by slicing twice, + one can express a slice by length operation.
+The pattern {#syntax#}[a .. a + b]{#endsyntax#} is always better expressed + {#syntax#}[a..][0..b]{#endsyntax#} because:
+The syntax {#syntax#}[:x]T{#endsyntax#} is a slice which has a runtime-known length diff --git a/doc/langref/slicing_by_length.zig b/doc/langref/slicing_by_length.zig new file mode 100644 index 0000000000000000000000000000000000000000..abb7d9394fd3978f694e9a58796a65926584e087 --- /dev/null +++ b/doc/langref/slicing_by_length.zig @@ -0,0 +1,12 @@ +const expectEqual = @import("std").testing.expectEqual; + +test "example" { + var array = [_]i32{ 1, 2, 3, 4 }; + var runtime_start: usize = 1; + _ = &runtime_start; + const length = 2; + const array_ptr_len = array[runtime_start..][0..length]; + try expectEqual(*[length]i32, @TypeOf(array_ptr_len)); +} + +// test diff --git a/doc/langref/test_basic_slices.zig b/doc/langref/test_basic_slices.zig index 28013148352eba7c5b9e6c0849e778c1ebc0b5ed..d627b7d0a6c1347ccebbf2f773de59630c91d063 100644 --- a/doc/langref/test_basic_slices.zig +++ b/doc/langref/test_basic_slices.zig @@ -21,15 +21,6 @@ test "basic slices" { const array_ptr = array[0..array.len]; try expectEqual(*[array.len]i32, @TypeOf(array_ptr)); - // You can perform a slice-by-length by slicing twice. This allows the compiler - // to perform some optimisations like recognising a comptime-known length when - // the start position is only known at runtime. - var runtime_start: usize = 1; - _ = &runtime_start; - const length = 2; - const array_ptr_len = array[runtime_start..][0..length]; - try expectEqual(*[length]i32, @TypeOf(array_ptr_len)); - // Using the address-of operator on a slice gives a single-item pointer. try expectEqual(*i32, @TypeOf(&slice[0])); // Using the `ptr` field gives a many-item pointer. -- 2.54.0