Is there a way to pass an allocator at compile time?
I am learning Zig by building a small Matrix library. For the initial version I
thought it would be good enough if every operation (e.g. adding two matrices
together) would allocate a Matrix for the result.
I don't want to pass an allocator to every matrix operation. Instead I would
like to pass an allocator at compile time.
So that a.add(allocator, b) becomes a.add(b). Is this possible?
I've tried:
const std = @import("std");
const Allocator = std.mem.Allocator;
const expect = std.testing.expect;
fn Matrix(comptime T: type, comptime allocator: Allocator) type {
return struct {
const Self = @This();
elements: []T = undefined,
allocator: Allocator = allocator,
rows: usize,
columns: usize,
pub fn init(rows: usize, columns: usize) !Self {
return Self{
.elements = try allocator.alloc(T, rows * columns),
.allocator = allocator,
.rows = rows,
.columns = columns,
};
}
};
}
pub const Mat = Matrix(
f32,
std.heap.ArenaAllocator.init(std.heap.page_allocator),
);
test "Initalize matrix" {
var m = Mat.init(16, 16);
_ = m;
}
This throws the following error:
tmp.zig:28:33: error: expected type 'mem.Allocator', found 'heap.arena_allocator.ArenaAllocator'
/nix/store/wrm7r7msb7yrhnwaxgbpn2mc7kla6x4a-zig-0.11.0/lib/zig/std/heap/arena_allocator.zig:8:28: note: struct declared here
/nix/store/wrm7r7msb7yrhnwaxgbpn2mc7kla6x4a-zig-0.11.0/lib/zig/std/mem/Allocator.zig:1:1: note: struct declared here
tmp.zig:5:49: note: parameter type declared here