Zig Vector Types
A vector type is a type that holds several values of one element type side by side. Each value sits in its own lane and all lanes move together.
Four integer lanes
This program builds a four-lane vector of integers and prints every lane in order.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const v: @Vector(4, i32) = .{ 10, 20, 30, 40 };
try out.print("{d} {d} {d} {d}", .{ v[0], v[1], v[2], v[3] });
}Eight lanes at once
This program builds an eight-lane vector and prints its first and last lanes.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const v: @Vector(8, i32) = .{ 1, 2, 3, 4, 5, 6, 7, 8 };
try out.print("{d} {d}", .{ v[0], v[7] });
}Vector and array
This program converts an array to a vector and back again, then prints two lanes of the result.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const arr: [4]i32 = .{ 3, 6, 9, 12 };
const v: @Vector(4, i32) = arr;
const back: [4]i32 = v;
try out.print("{d} {d}", .{ back[1], back[2] });
}Example
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const color: @Vector(4, i32) = .{ 255, 128, 0, 255 };
try out.print("{d} {d} {d} {d}", .{ color[0], color[1], color[2], color[3] });
}Key points
- Lane: a lane is one slot in a vector.
- Vector type: a vector type is written as @Vector with a lane count and an element type in parentheses.
- The lane count is a power of two, so counts like 4 and 8 are valid while 3 and 5 are not.
- A vector literal lists one value per lane inside braces, in lane order.
- Indexing: indexing is reading one lane with its position number.
- An array and a vector of the same length and element type convert directly to each other.
The code builds a four-lane vector holding four channel values. Each number sits in one lane, in order. Printing reads the lanes in order, so the output matches the literal.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does @Vector(4, i32) hold?