Is there a pre-existing way to choose the output type of a serde deserialization?

I have a Cargo project, and I want to write a binary that will take in a type name and a YAML string, and attempt to deserialize the YAML to the type, and report whether deserializing succeeded. My use case is that there is some YAML in non-Rust documentation, and I'd like to automatically test that it is in the correct format.

I know that I can do this by using brute force if or match statements, etc. I just wanted to make sure I didn't re-invent something that already existed.

I'm not 100% sure, but if you are asking whether there is runtime reflection to reify a type based on its name, then no, there's no such functionality in the language.

1 Like

You might be able to get somewhere with the typetag crate, but I'm not familiar enough with it to propose a concrete solution.

Full runtime reflection would probably be more powerful than I need; I was more looking for something that would help me build the scaffolding to branch out. I assume I could do this with a macro, but I'm not great with those yet.

Intriguing! I have a feeling it might not work in this case since I'd have to re-work the YAML to fit the tag style; but I'll take a closer look.

If you are satisfied with a macro, then that's easy, except you can only deserialize into a predefined list of types. Playground.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.