worldline-go / struct2

convert struct to map with custom hook functions
https://pkg.go.dev/github.com/worldline-go/struct2
MIT License
20 stars 3 forks source link

`ptr2` creating Zero value when pointer is `nil` #11

Closed Dragomir-Ivanov closed 7 months ago

Dragomir-Ivanov commented 10 months ago

Greetings, More corner cases when using this lovely package.

Having a struct like:

type S struct {
    at    *time.Time `struct: ,ptr2`
}

Then decode this struct to map, at becomes 01-01-0001..., which is not ideal. One could argue the hole point to use pointers is to have be able to have optional fields (when using json: ,ptr2, omitempty, when json is backup tag name), or nullable fields(when using json: ,ptr2.

The example above behaves exactly if I had:

type S struct {
    at    time.Time
}

My proposal is to remove Zero type creating in func Ptr2Concrete(val interface{}) interface{} { function, and just return pointer value(which is nil).

rytsh commented 10 months ago

Hi @Dragomir-Ivanov, I like that approach but to preventing old behavior can I create another field name called ptr is the new functionality of ptr2 and create new function for Ptr2Concrete

So when you have

x := struct {
  Time *time.Time `struct:"time,ptr"`
}{}

This will be encode to

map[string]interface {}{"time":<nil>}

What you think about that? And I guess that nil should be real nil not (*time.Time)(nil) to make checks == nil easily, do we need type of nil in that time?

Dragomir-Ivanov commented 10 months ago

Hi @rytsh, I am totally fine with adding new ptr tag, along with encoding to plain nil instead of (*time.Time)(nil). I am willing to work on this during the holidays, so I will send PR. I am so happy that this project is still alive!

Also, I am adding more Config options to struct2 behind the scenes, in order for it to be usable reasonably well without any struct field tags. Will make PR for it when ready.

Thank you, and happy holidays!