I’m trying to create a generic function in Motoko that converts any variant value to its text representation. For instance, converting a variant #xyz to the string "xyz"
Pattern matching won’t work since this needs to be generic across any variant type.
I tried using debug_show with Any type, but received the error: show is not defined for operand type Any
Is there currently a way to implement this functionality in Motoko, or is this not possible with the language’s current features?
If you check out @Gekctek 's cbor and candid packages you’ll see some loving that may be useful. I think @tomijaga maybhave had a serde library as well. The issue is that the text gets hashed somewhat is in candid is a number. If you have the library of possible values the libraries match them up I think, but I’m guessing that you want something more generic where you may not know the names.
A few solutions have been proposed in the past including a standard that would ask motoko devs to have a property of their class/library that exposes these. I’m not sure why reflection is such a hot button issue…it would make sense to me stir it would be an easy thing to add to the compiler to pull all the string keys for a variant types.
We’ve asked for it in the past and it seems there are lots of useful places where reflection(of types and classes as well) would be very useful.
When i did my research to try to implement a good serializer in Motoko I looked at things like serde in Rust and saw that reflection is compile-time vs runtime. This seems important because of the runtime performance but also other things like type safety which is important in languages like Rust and Motoko.
Essentially we need something like in Rust where we can have ‘macros’ that create the mapping code at compile-time using reflection
But as of right now, everything is manual, so youll have to use pattern matching or maybe get creative with to_candid/from_candid, because that is the only way to serialize without manual mapping as of now