#Creating recursive types with @Type?

1 messages · Page 1 of 1 (latest)

fathom jewel
#

Can you create recursive types with @Type? e.g. a TreeNode type that contains a pointer to TreeNode

According to https://github.com/ziglang/zig/issues/6211, naively creating a recursive type by naming the type inside @typeInfo won't work - but is there a hackier way to construct a recursive type?

GitHub

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software. - Issues · ziglang/zig

unique dawn
#

perhaps @This() is what you're looking for

fathom jewel
#

I'm talking about constructing a type from std.builtin.Type with @Type, not just writing a recursive struct - @This() won't work here unless i'm misunderstanding how it works

remote remnant
#

The linked issue https://github.com/ziglang/zig/issues/6211 is 3 years old and does not compile with current version of the compiler. I added a comment to the issue with the example updated for the current zig-0.12-dev and it is still has the same problem:

foo.zig:5:1: error: dependency loop detected
const Node = @Type(.{
^~~~~
GitHub

This doesn't work: const Node = @Type(.{ .Struct = .{ .layout = .Auto, .fields = &[_]TypeInfo.StructField{ .{ .name = "next", .field_type = *Node, .default_value = null, }, }, .de...

pallid sonnet
#

I haven't thought a lot about this, so I think there might be good cases to use this, I just am currently struggling to come up with examples, what are situations where you want to use this?

#

Also probably not a satisfying answer but I think the current way to do this is via a build step that generates code or manually.

#

The only thing I can come up with that might need something like this may be some kind of generic n-ary tree with named branches, or something like that, that seems to be a level of meta programming that may warrant a custom build step. Maybe I am currently too tired and not thinking of more obvious ways this would be used.

#

Otherwise can't you just write the tree part as a recursive struct and then embed the @Type part as a field by passing it as the T param to the type constructing function? You might not end up with a "flattened" type and have a extra node.val.fielda instead of node.fielda but that seems fine.