During the study and practice of optionals and pointers in Zig, I encountered behavior that was quite unclear to me. I can't quite understand what exactly the compiler is trying to tell me.
In the code, I have an Optional next where I want to assign a memory reference or say that it is nullable. However, the compiler gives me the following error:
error: expected type '?*SinglyLinkedList.Node', found '*const SinglyLinkedList.Node'
currentNode.*.next = &newNode;
I can't fully understand why const
is used here instead of Optional
(?
).
const Node = struct {
value: u8,
next: ?*Node,
};
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
var head = Node{
.value = 0,
.next = null,
};
addNode(&head, 1);
addNode(&head, 2);
addNode(&head, 3);
// printList(head);
try stdout.print("Hello, {s}!\n", .{"world"});
}
pub fn addNode(head: *Node, value: u8) !void {
var currentNode = head;
while (currentNode.*.next != null) {
currentNode = currentNode.*.next orelse break;
}
const newNode = Node{
.value = value,
.next = null,
};
currentNode.*.next = &newNode orelse unreachable;
}
Based on the error, I thought I shouldn't use
orelse
and should just use &newNode
. But it still shows the error.
Zig version is 0.14.0.