zig

Initialising a nullable array struct field in zig 0.14.0


I'm using zig 0.14.0, and having issues with setting a nullable array. I've come up with an example (this is not my main code base or anything close to what I'm doing) to illustrate the issue.

const std = @import("std");

const Node = struct {
    children: ?[]Node = null,
    data: u8,
};

pub fn main() void {
    // Creating child nodes
    const child1 = Node{ .data = 1 };
    const child2 = Node{ .data = 2 };

    // Creating a parent node with children
    const parent_with_children = Node{
        .children = &[_]Node{ child1, child2 },
        .data = 0,
    };

    // Creating a parent node without children (null array)
    const parent_without_children = Node{
        .data = 0,
    };

    std.debug.print("With Children {any}\n", .{parent_with_children});
    std.debug.print("Without Children {any}\n", .{parent_without_children});
}

When compiling, I get the error:

src/main.zig:15:10: error: expected type '?[]main.Node', found '*const [2]main.Node'
        .children = &[_]Node{ child1, child2 },
        ~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Is there a way to do this? Is this a bug? Or what's the best way to get around this (I have access to the source code for the original struct).


Solution

  • You can't assign a literal &[_]Node{ child1, child2 } which is constant to a mutable slice []Node and by extension not to a nullable mutable slice.

    You could change your struct to store a const slice:

    const Node = struct {
        children: ?[]const Node = null,
        data: u8,
    };
    

    or you have to use a non-const location you can get a mutable slice from:

    
    pub fn main() void {
        // Creating child nodes
        const child1 = Node{ .data = 1 };
        const child2 = Node{ .data = 2 };
    
        var children = [_]Node{ child1, child2 };
    
        // Creating a parent node with children
        const parent_with_children = Node{
            .children = &children,
            .data = 0,
        };
        //…
    }