Embedding in input/output structs with omitting fields #118
-
Is it possible to omit some fields of embedded struct in input and output interactor structs? Solution with
If omiting fields is not possible - any other best practice to avoid repeating same field definition on every struct that uses this field (i.e. in above example we try to |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Mentioned solution works for marshaling in some conditions, however it is possible to have a value that results in an package main
import (
"encoding/json"
"fmt"
)
func main() {
type omit *struct{}
type Item struct {
ID uint64 `json:"id" required:"true"`
Name string `json:"name" required:"true"`
}
type ItemCreateRequest struct {
Item
ID omit `json:"id,omitempty"`
}
ic := ItemCreateRequest{}
ic.Item.ID = 123
ic.Item.Name = "abc"
ic.ID = &struct{}{}
j, _ := json.MarshalIndent(ic, "", " ")
fmt.Println(string(j))
} {
"name": "abc",
"id": {}
} It means, that static schema of such field would be I personally prefer precise composition with field groups to hiding fields: type ItemData struct {
Name string `json:"name" required:"true"`
}
type Item struct {
ID uint64 `json:"id" required:"true"`
ItemData
}
type ItemCreateRequest = ItemData |
Beta Was this translation helpful? Give feedback.
-
Thanks for answer.
This works but was hoping to avoid "quirks" like
when creating structs with literals. |
Beta Was this translation helpful? Give feedback.
Mentioned solution works for marshaling in some conditions, however it is possible to have a value that results in an
object
for an "omitted" field:It means, that static schema of such field would be
{"type":"object"}
, not absence of fiel…