#Dual argument types

1 messages · Page 1 of 1 (latest)

wary birch
#

I have a function and i want to pass an argument that can be one of two types.
both types have a common filed called name (which is also of the same type).
i could create a union and then just switch on the types and extract the field.
just wondering if there were more way to do this in zig., like using anytype or something else.
if you wanna share ur thoughts, thanks.

pub fn Walker(comptime T: type) type {
    return struct {
        source: *T,
        const Self = @This();
        // ...rest of the struct props

        fn visitDefinition(self: *Self, node: DefinitionNode) anyerror!void {
            if (node.fields) |fields| {
                for (fields) |field| {
                    try self.visitField(field, node);
                }
            }
            // ...
        }
        fn visitExtension(self: *Self, node: ExtensionNode) anyerror!void {
            if (node.fields) |fields| {
                for (fields) |field| {
                    try self.visitField(field, node);
                }
            }
            // ...
        }
        fn visitField(self: *Self, node: FieldNode, parent: /* here... union, anytype, what else could we do? */) anyerror!void {
            const p_id = parent.name.id; // here name is the same on both parent types. 
            // ...
        }
    };
}
thin thistle
#

i mean if you use anytype it will be duck-typed, so accessing a field that’s the same name and type will just work