最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I correctly use Optional with pointers in Zig to avoid const errors? - Stack Overflow

programmeradmin3浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论