我在这个例子中做错了什么?在deinit()
中,我得到一个错误,预期是*MemoryPool
,但*const MemoryPool
是给定的。
const Tree = struct {
node_pool: std.heap.MemoryPool(Node),
pub fn init(allocator: Allocator) Tree {
var node_pool = std.heap.MemoryPool(Node).init(allocator);
return Tree{ .node_pool = node_pool };
}
pub fn deinit(self: Tree) void {
self.node_pool.deinit(); // <-- error: * is expected, *const is given
}
};
我正在围绕@constCast()
的错误工作,但这感觉很奇怪-我不完全明白为什么我这样做,我想我可能正在做一些非常错误的事情。有办法避免吗?我错过什么了吗?
const Tree = struct {
...
pub fn deinit(self: Tree) void {
@constCast(&self.node_pool).deinit();
}
};
函数参数在Zig中是不可变的。这就是为什么有const
。
你需要给deinit
提供一个指向Tree
的指针:
pub fn deinit(self: *Tree) void {
self.node_pool.deinit();
}
另外,您可以执行self.* = undefined
来使特定的Tree
实例无效。这通常由STD类型完成。