Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mutate a Zig function argument?

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();    
}
like image 293
Erik Engheim Avatar asked Mar 30 '26 22:03

Erik Engheim


1 Answers

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 {
    // ...
}
like image 133
sigod Avatar answered Apr 02 '26 14:04

sigod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!