I’m a bit confused as to how const works. For example, the below has the assignment child1_node.left_child = &child2_node; fail because error: cannot assign to constant
I thought, “OK, makes sense as my struct definition has left_child as const”. So, I attempted to remove that restriction. However, if I do that, then when I am creating predefined_nodes it dies because expected type ‘?*const_node.Node’, found ‘*const const_node.Node’.
I.e., it seems one situation wants me to have it const and another doesn’t. Is there any reconcillation for this? In my mind, predefined node is initialized into memory on application start up. Then, I write to one of the positions by use of the pointer. Is that predefined_nodes in static memory or something such that being able to assign at all is folly?
When you declare child1_node as const it means that it’s fields must stay constant.
When you write child1_node.left_child = … you are trying to mutate that variable.
declaring child1_node as var should fix that.
So, any anonymous(?) “object” (i.e. not bound) is intrinsically const. So, I first must define the left node explicitly and as a var before taking its address. Will try that.
Edit: actually, doesn’t that mean you can’t have a nested ‘predefined_nodes’? Notice how I had one more layer of depth than your example. To have a deeper nest I’d need &[_]Node which would yield the const issue.
What you might be missing is that when you have a mutable pointer, it has to point to a mutable value that is stored somewhere. Either that value is declared/stored on the stack or allocated on the heap. It cannot be a compile time constant, since then it cannot be mutable.
Unlike some languages (e.g., Rust), Zig does not automatically copy a compile time constant into a hidden/anonymous stack variable as part of an expression. You have to declare it as a local var. Zig’s approach is more explicit.