| ... | ... | @@ -1955,7 +1955,7 @@ or |
| 1955 | 1955 | TODO talk about C ABI interop<br> |
| 1956 | 1956 | TODO consider suggesting std.MultiArrayList |
| 1957 | 1957 | </p> |
| 1958 | | {#see_also|@splat|@shuffle|@select|@reduce#} |
| 1958 | {#see_also|@splat|@shuffle|@select|@reduce|Slicing by Length#} |
| 1959 | 1959 | |
| 1960 | 1960 | {#header_open|Relationship with Arrays#} |
| 1961 | 1961 | <p>Vectors and {#link|Arrays#} each have a well-defined <strong>bit layout</strong> |
| ... | ... | @@ -2150,6 +2150,24 @@ or |
| 2150 | 2150 | |
| 2151 | 2151 | {#see_also|Pointers|for|Arrays#} |
| 2152 | 2152 | |
| 2153 | {#header_open|Slicing by Length#} |
| 2154 | <p>Even though Zig only has syntax for slicing based on start and end indices, by slicing twice, |
| 2155 | one can express a <strong>slice by length</strong> operation.</p> |
| 2156 | <p>The pattern {#syntax#}[a .. a + b]{#endsyntax#} is always better expressed |
| 2157 | {#syntax#}[a..][0..b]{#endsyntax#} because:</p> |
| 2158 | <ul> |
| 2159 | <li>Slices are represented in memory as a pointer and length. Despite |
| 2160 | syntactically appearing as twice the work, it is actually one less |
| 2161 | subtraction in machine code.</li> |
| 2162 | <li>If {#syntax#}a{#endsyntax#} is known at runtime and |
| 2163 | {#syntax#}b{#endsyntax#} is known at {#link|comptime#}, the former |
| 2164 | results in a slice but the latter results in a single-item |
| 2165 | {#link|pointer|Pointers#} to an {#link|array|Arrays#}, a generally more |
| 2166 | safe type because the length is compile-time known.</li> |
| 2167 | </ul> |
| 2168 | {#code|slicing_by_length.zig#} |
| 2169 | {#header_close#} |
| 2170 | |
| 2153 | 2171 | {#header_open|Sentinel-Terminated Slices#} |
| 2154 | 2172 | <p> |
| 2155 | 2173 | The syntax {#syntax#}[:x]T{#endsyntax#} is a slice which has a runtime-known length |