Skip to content
This repository has been archived by the owner on Jul 22, 2024. It is now read-only.

Allow types to determine how to decode themselves #294

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

mthjs
Copy link

@mthjs mthjs commented Jun 27, 2022

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 #115

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

@wrouesnel
Copy link

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?

@andig
Copy link

andig commented Sep 29, 2022

+1 for allowing objects to decode themselves.

Similar to the `UnarshalX` family of functions seen throughout
`encoding` and `encoding/json`, include the name of what is being
decoded into the function.
@mthjs
Copy link
Author

mthjs commented Dec 15, 2022

@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.

@stephen-slm
Copy link

@mitchellh any interest in this being merged?

@dplepage-dd
Copy link

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.

if outVal.CanAddr() {
v := outVal.Addr()
if u, ok := v.Interface().(decoder); ok {
return u.DecodeMapstructure(input)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it might make more sense to put this after the DecodeHook, so that any custom preprocessing can still happen.

@pcfreak30
Copy link

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 added a commit to LumeWeb/mapstructure that referenced this pull request Jun 3, 2024
@buzzdan
Copy link

buzzdan commented Jun 26, 2024

@pcfreak30 @mitchellh any updates on this one ?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Implement JSON like unmarshaling interface
7 participants