Vector 可以用來儲存一組相同型別的資料,其長度和型別需在宣告時指定且不能變更,支援 SIMD(Single instruction, multiple data)。
基礎
使用 @Vector(L, T) 宣告,其中 L 代表長度,T 代表型別,可以是布林、整數、浮點數、指標。
注意 Vector 不像 Array 和 Slice 那樣擁有 .len 欄位,也無法使用 for 迴圈遍歷。
const print = @import("std").debug.print;
pub fn main() void { const a: @Vector(3, i8) = .{ 1, 1, 5 }; const b: @Vector(3, i8) = .{ 2, 5, -10 }; const c = a + b; print("{}, {}, {}", .{ c[0], c[1], c[2] });}3, 6, -5運算
Vector 支援各種運算:
- 算數:
+,-,/,*,@divFloor,@sqrt,@ceil,@log, etc. - 位元操作:
>>,<<,&,|,~, etc. - 比較:
<,>,==, etc.
const print = @import("std").debug.print;
pub fn main() void { const a: @Vector(3, i8) = .{ 1, 1, 5 }; const b: @Vector(3, i8) = .{ 2, 5, -10 }; const c = a * b; print("{}, {}, {}", .{ c[0], c[1], c[2] });}2, 5, -50填充
如果你需要用相同數值填滿整個 Vector,可以用 @splat(V),其中 V 就是要填入的數值。
const print = @import("std").debug.print;
pub fn main() void { const a: @Vector(3, i8) = .{ 1, 1, 5 }; const b: @Vector(3, i8) = @splat(2); const c = a + b; print("{}, {}, {}", .{ c[0], c[1], c[2] });}3, 3, 7陣列
Vector 和 Array 可以互相轉換。
const print = @import("std").debug.print;
pub fn main() void { const arr = [_]i8{ 1, 2, 3 }; const vec: @Vector(3, i8) = arr; print("{}, {}, {}", .{ vec[0], vec[1], vec[2] });}const print = @import("std").debug.print;
pub fn main() void { const vec: @Vector(3, i8) = .{ 1, 2, 3 }; const arr: [3]i8 = vec; print("{}, {}, {}", .{ arr[0], arr[1], arr[2] });}1, 2, 3參考
本文以 Zig 0.13.0 為主。並同時發佈在: