0

What am I doing wrong in this example? In deinit() I am getting an error that expected is *MemoryPool but *const MemoryPool was given.

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
    }
};

I'm working around the error with @constCast() but this feels strange - I don't fully understand why I'm doing this and I assume I might be doing something very much wrong. Is there a way to avoid it? Am I missing something?

const Tree = struct {
    ...

    pub fn deinit(self: Tree) void {
        @constCast(&self.node_pool).deinit();
    }
};
sigod
  • 3,514
  • 2
  • 21
  • 44
Ski
  • 14,197
  • 3
  • 54
  • 64

1 Answers1

1

Function parameters are immutable in Zig. That's why there's const.

You need to provide deinit with a pointer to Tree:

pub fn deinit(self: *Tree) void {
    self.node_pool.deinit();
}

Additionally, you can do self.* = undefined to invalidate a specific Tree instance. This is commonly done by STD types.

sigod
  • 3,514
  • 2
  • 21
  • 44
  • 1
    Earlier I changed from `*Tree` to `Tree` without thinking too much ‍♂️ as I was getting compile error earlier of same kind. Reason was because I declared my tree instance using `const tree = Tree.init(...)`. Changed it now to `var tree = Tree.init(...)` and problems gone. Thank you. – Ski Mar 30 '23 at 15:07