mapstructure icon indicating copy to clipboard operation
mapstructure copied to clipboard

Allow types to determine how to decode themselves

Open mthjs opened this issue 2 years ago • 7 comments

When the destination of a decode implements the custom decoder interface, use said interface. Custom decoders take precedence over the default decoding rules.

This should resolve https://github.com/mitchellh/mapstructure/issues/115

Renamed the master -> main which closed the pull-request, sorry :sweat_smile:

mthjs avatar Jun 27 '22 09:06 mthjs

I'd like to see this merged, though to offer one comment, the interface function - Decode() might be a bit too generic within the go-ecosystem? MapStructureDecode maybe?

wrouesnel avatar Aug 06 '22 02:08 wrouesnel

+1 for allowing objects to decode themselves.

andig avatar Sep 29 '22 16:09 andig

@wrouesnel I've applied your suggestion although I did swap the order. Like any of the standard-libraries UnmarshalX functions, I've opted to suffix the expected Decode function with Mapstructure instead of prefixing it.

mthjs avatar Dec 15 '22 14:12 mthjs

@mitchellh any interest in this being merged?

stephen-slm avatar Jan 29 '24 16:01 stephen-slm

Would it be possible to make this work in both directions, so that e.g. decoding a Someone into an interface{} produces a string (the same way json allows customizing both MarshallJSON and UnmarshallJSON)?

There would be some ambiguity, I guess, since you could conceivably call Decode(x,y) with x and y both being types with custom encoder/decoders, but in practice I think it's rarely used as a generic converter, it's almost always either decoding from a map structure to a custom type or encoding from a custom type back to a map structure, so it would probably be fine to just error out in case of conflicting custom handlers.

dplepage-dd avatar Mar 14 '24 16:03 dplepage-dd

Bumping this b/c this would probably simplify my code a lot to use stdlib marshal interfaces and only 1 hook for it all.

pcfreak30 avatar May 19 '24 22:05 pcfreak30

@pcfreak30 @mitchellh any updates on this one ?

buzzdan avatar Jun 26 '24 09:06 buzzdan