Essentially, I want to be able to pass data to a function, and have it be one of any number of structs I’ve defined, and let the function decide how to handle the data depending on what kind of struct it is.
For example, if I have a function that takes a type, along with a value of that type:
pub fn handler(comptime T: type, data: T) {
std.debug.assert(@typeInfo(T) == .Struct);
// ... switch on T struct type?
}
// at call site
const d1: MyCustomStruct = .{ ... };
handler(MyCustomStruct, d1);
// or
const d2: AnotherCustomStruct = .{ ... };
handler(AnotherCustomStruct, d2);
// or
const d3: TestStruct = .{ ... };
handler(TestStruct, d3);
How can handler() know which struct type was passed to it?
Interesting, that makes sense. Though that checks against the type T, rather than the actual data. I guess within each switch case the data parameter would have to be manually cast to the specific type? Or is there a way to capture the data in the indicated type as part of the switch?
Remember that your data parameter is already known to be of type T, so you just access its fields and methods directly within each switch prong. The compiler will not compile if you try to access a field or method that doesn’t exist for the type; that’s what’s commonly referred to as compile-time duck-typing in Zig.