Allocate struct pointers fields with "bind" tag #1165
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hello,
this is an attempt to fix #1164.
If I were to do something like:
It wouldn't have worked prior to this PR because
bind
would've created a zeroed instance of the struct and then attempted to get areflect.Value
by dereferencing theUser
field. But in a zeroed struct the pointer is nil, and so you get this panic:A workaround would be to embed
models.User
without a pointer. But this is not always feasible or performant, depending on how the resulting slice is going to be used afterward.This PR makes it so that
bind
also allocates any pointer field provided that the target is[]*Struct
and thebind
tag is set.Implementation wise, I simply enumerate the struct fields after the call to
reflect.New
and allocate any pointer with thebind
tag.When the
bind
target is[]Struct
(instead of[]*Struct
) the behavior remains unchanged as the structs are copied-by-value anyways and the documentation already warns about not using structs with references when binding like that.