为什么我需要constCast这里,有更好的方法吗?



我在这个例子中做错了什么?在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类型完成。

最新更新