admin管理员组文章数量:1355570
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.
本文标签: How do I correctly use Optional with pointers in Zig to avoid const errorsStack Overflow
版权声明:本文标题:How do I correctly use Optional with pointers in Zig to avoid const errors? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743981650a2571107.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论