I have structs and classes that I’d like to be able to easily create from strings in a generic fashion, using the to!T(string) method. However, I’m not sure how I could ‘override’ the method to get this kind of behavior. Going from my type to the string is easy (I would just define opCast(string)), but is what I’m looking for even possible?
I have structs and classes that I’d like to be able to easily create
Share
Don’t define an
opCastforstringif you want your type to convert tostring. That’s whattoStringis for.writelnandformatand the like usetoString, not casting orto, andtowill usetoString, so it’s definitely better to definetoStringfor converting to tostring. You defineopCastfor converting to types other thanstring. Then you can use that with casting or withto.Now, if you want to convert a
stringto your user-defined type, then just define the appropriate constructor, and that will work withto.