I have the following types:
const ParsedValType = enum { String, Integer, List, Dict };
const ParsedVal = union(enum) {
String: []const u8,
Integer: i64,
List: []const ParsedVal,
Dict: []DictEntry,
};
const DictEntry = struct { k: []const u8, v: ParsedVal };
I am having big trouble prototyping in Zig and I am wasting a reasonable amount of time on something which should be relatively easy to do. I would like to somehow initialize a literal slice, so I can play around with it by doing the following:
var x = &[_]ParsedVal{
.{ .String = "string here" },
.{ .Integer = 55 },
.{ .List = []const ParsedVal{ .String = "asdfsdf" } },
};
That code works fine for the .String
and .Integer
, however when I try to run the program with .List
I get the following error:
error: type '[]const main.ParsedVal' does not support struct initialization syntax
.{ .List = []const ParsedVal{ .String = "asdfsdf" } },
~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
I have tried many different variations to initialize the .List
field, but without success.
How can I just initalize a literal slice and then loop on it like that:
for (x) |val| {
switch (val) {
.String => |s| std.debug.print("string: {s}\n", .{s}),
.Integer => |d| std.debug.print("integer: {d}\n", .{d}),
.List => |l| std.debug.print("list {any}\n", .{l}),
.Dict => |d| std.debug.print("dictionary {any}\n", .{d}),
}
}
The correct syntax for an array literal coerced to slice is:
&[_]TheType{ value1, value2, ... }
And each value needs its own initialization syntax. E.g. ParsedVal{ .String = "..." }
or, using anonymous union literals syntax, .{ .String = "..." }
.
The corrected syntax for initializing the .List
field looks like this:
.{ .List = &[_]ParsedVal{ .{ .String = "asdfsdf" } } }