Questions about mutability, lambdas and many-item pointers

Welcome to Ziggit!

1

Currently, taking the pointer of a variable (with &) is enough to not get the error, even if the variable is not actually modified though this pointer.

One reason for this is that this check happens in an early stage of the compiler, where the compiler does not yet know much about the behavior of other functions. See also this topic for a similar question.

But even if the check would do more complex analysation of the code, it’s impossible to say for every case if a variable could get modified, or if it will never be modified. For example:

const tm: TuringMachine = ...;

pub fn main() void {
    var x = false;
    tm.run();
    x = true;
}

The variable will not be modified if the turing machine does not halt. But it’s impossible to know if that’s the case or not.

2

You can usually just define the labda function seperately as a normal function. I think the exception is when the labda function uses comptime parameters of the outer function, though I can’t currently think of a good example where this is the case. So there may be use cases where this is a good solution, but it’s rare.

3

In C, a pointer is used both to point to a single item and to point to an array. In zig, there are multiple pointer types for this. So it’s at least needed for interaction with C, because C functions may expect multi-item pointers.

In zig, you often use slices, which is a multi-item pointer with a length.

There are some cases though where it makes sense to use a multi-item pointer instead of a slice, usually because the length is already stored elsewhere. For example:

const Image = struct {
    width: usize,
    height: usize,
    data: [*]Color,
};

data could also be a slice, but the length is already implied by width * height, so it’s not needed to store it.

3 Likes