Usage example of `std.meta.declList`

Is there an example of how to use std.meta.declList?

Looking at the source code just makes me more confused than ever. It looks like the Decl type parameter should contain at least a “name” field, but it is quite guaranteed not to work, if used that way.

I tried something like:

pub fn main() !void {
    std.meta.declList(@This(), struct { name: []const u8 });
}

but it actually does not work… To me, it actually looks like there is no way to make it work.

Do any of you have any pointers?

It’s the strangest zig function I ever seen.

declList second argument is the type of the declarations.
For a namespace with:

pub fn foo() void {
}

the type is fn() void.

It looks like there is none:

/opt/zig-0.12/lib$ grep -rI declList
std/meta.zig:pub fn declList(comptime Namespace: type, comptime Decl: type) []const *const Decl {

And that’s all, only function declaration. If it is not used in std lib itself , it 's very unlikely it is used in someone’s project.

I don’t also know std.meta.declList specification.

I’ve test following…

var / const in the container is also declaration.
But mixed declarations of var / const does not permit.

const A = struct {
    pub var x: usize = 42;
    pub const y: usize = 42;
};

pub fn main() void {
    comptime {
        _ std.meta.declList(A, usize); // Compile error !!!
    }
}

All of the same declarations is ok !

const A = struct {
    pub var x: usize = 42;
    pub var y: usize = 21;
};

I found this: Take advantage of new HashMap API's preserving order by Vexu · Pull Request #5847 · ziglang/zig · GitHub

So maybe the plan is to get rid of the function.


I also think that link above explains that function, it seemed that this existed because there where hash maps used for declarations that lost the order of the declarations, (and it seems declList was used to sort that unordered hash maps keys to get a stable ordering), but that change made it so that the used hash map preserved the ordering, which is why they then had a stable ordering, no longer needing to create a stable ordering artificially through sorting.

I think you are better of using something like @typeInfo(A).Struct.decls.
It may make sense to create an issue about deprecating/removing that function.

2 Likes