Creating a constant tree structure

I want to create a constant tree structure.
The struct looks like this:

pub const Command = struct {
    long: []const u8,
    short: [4]u8 = undefined,
    subcommands: []const Command,
};

I create a tree like this:

pub var CommandTree: []Command = &.{
    .{
        .long = "System",
        .subcommands = &.{
            .{
                .long = "Error",
                .subcommands = &.{
                    .{ .long = "Next", .subcommands = &.{} },
                },
            },
            .{ .long = "Version", .subcommands = &.{} },
        },
    },
.....

now i get an compile error

expected type '[]scpi.Command', found '*const [2]scpi.Command'
pub const CommandTree: []Command = &.{

by adding const to the slice

pub var CommandTree: []const Command = &.{

the error dissapears, but now i cant fill in the .short field, which i want to derive from .long at compile time.

Is it even possible to create a tree structure like this, that can be manipulated at compile time. Thanks in advance.

You can have a compile-time function return a Command while deriving the .short field.

fn Cmd(comptime long: []const u8, comptime subcmds: []const Command) Command {
    return .{
        .long = long,
        .short = derive_from(long),
        .subcommands = subcmds,
    };
}

pub const CommandTree: []const Command = &.{
    Cmd("System", &.{
        Cmd("Error", &.{
            Cmd("Next", &.{}),
         }),
        Cmd("Version", &.{}),
    }),
};
4 Likes