Vectors
Vectors support the same builtin operators as their underlying base types. These operations are performed element-wise, and return a vector of the same length as the input vectors. This includes:
- Arithmetic (
+
,-
,/
,*
,@divFloor
,@sqrt
, ,@log
, etc.) - Bitwise operators (
>>
,<<
,&
,|
,~
, etc.) - Comparison operators (,
>
,==
, etc.)
It is prohibited to use a math operator on a mixture of scalars (individual numbers) and vectors. Zig provides the builtin to easily convert from scalars to vectors, and it supports @reduce and array indexing syntax to convert from vectors to scalars. Vectors also support assignment to and from fixed-length arrays with comptime known length.
Operations on vectors shorter than the target machine’s native SIMD size will typically compile to single SIMD instructions, while vectors longer than the target machine’s native SIMD size will compile to multiple SIMD instructions. If a given operation doesn’t have SIMD support on the target architecture, the compiler will default to operating on each vector element one at a time. Zig supports any comptime-known vector length up to 2^32-1, although small powers of two (2-64) are most typical. Note that excessively long vector lengths (e.g. 2^20) may result in compiler crashes on current versions of Zig.
vector_example.zig
1/2 test "Basic vector usage"... OK
2/2 test "Conversion between vectors, arrays, and slices"... OK
All 2 tests passed.
TODO talk about C ABI interop
TODO consider suggesting std.MultiArrayList
See also: