#Need mutable map for deinit, but told it's const

1 messages · Page 1 of 1 (latest)

nimble pasture
#
    fn clear(self: @This(), alloc: std.mem.Allocator) @This() {
        switch (self) {
            .Str => |s| alloc.free(s),
            .Arr => |a| {
                for (a) |v| {
                    _ = v.clear(alloc);
                }
                alloc.free(a);
            },
            .Map => |m| {
                var it = m.iterator();
                while (it.next()) |kv| {
                    alloc.free(kv.key_ptr.*);
                    _ = kv.value_ptr.*.clear(alloc);
                }
                (&m).deinit(); // <-- HERE
            },
            else => {},
        }
        return .{ .Int = 0 };
    }

In a recursive structure I'm trying to make sure all memory is cleared safely,

I'm being told that &m is *const array_hash_map, but I want it to be mut.

How can I fix this?

novel rampart
#

I'm being told that &m is *const array_hash_map
correct, capture variables like |m| are immutable so taking a pointer to it also yields a const pointer
you would need to capture a pointer |*m| to be able to modify the value

vernal wadi
#

Also you're using self: @This() for your clear fn, and it seems that m.deinit() requires the self.Map to be mutable (e.g. use self: *@This() because of m.deinit(), and you might also have to use switch(self.*))

flat dock
#

afaik (&foo).bar is always unnecessary, and the dereference on the value_ptr isnt necessary either, you can just value_ptr.clear(alloc)