5

I have discovered that Zig function parameters are constant. That means my naive function for freeing a HashMap doesn't work. You can see an example of the code here. I am wondering if the most correct Zig way is to pass dict as a function or if there is some other way in which I can make a parameter mutable.

const Dict = std.StringHashMap;

fn releaseDict(allocator: Allocator, dict:  Dict(i16)) void {
    var iter = dict.iterator();
    while (iter.next()) |entry|
        allocator.free(entry.key_ptr.*);
    dict.deinit();    
}
Erik Engheim
  • 8,182
  • 4
  • 36
  • 51

1 Answers1

7

You don't. Function parameters are immutable by design:

Structs, unions, and arrays can sometimes be more efficiently passed as a reference, since a copy could be arbitrarily expensive depending on the size. When these types are passed as parameters, Zig may choose to copy and pass by value, or pass by reference, whichever way Zig decides will be faster. This is made possible, in part, by the fact that parameters are immutable.

Modifying function parameters can easily lead to unexpected results. If the parameter is passed by value (a copy of it is made), modifying it would not modify the original value.

What you want to do here is: pass a pointer to your hash map. E.g.

fn releaseDict(allocator: Allocator, dict: *std.StringHashMap(i16)) void {
    // ...
}
sigod
  • 3,514
  • 2
  • 21
  • 44