Skip to content

Embedding in input/output structs with omitting fields #118

Answered by vearutop
pboguslawski asked this question in Q&A
Discussion options

You must be logged in to vote

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:

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 {"type":"object"}, not absence of fiel…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by pboguslawski
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants