type Parent struct {
Name string `json:"parent_name"`
}
type Child struct {
Parent
}
Say I have two structs Parent
and Child
. I have two endpoints that read json
using those two structs.
// Sample Parent endpoint payload
{
"parent_name": "Parent Name"
}
// Sample Child endpoint payload
{
"child_name": "Child Name"
}
Both structs are being used to store similar data, but the json
key is different for each endpoint payload. Is there a way to edit the json
tag on the Child
struct such that Child
still inherits from Parent
, but the tag is now json:"child_name"
?
Go doesn't have inheritance, only composition. Instead of parent-child relationship think about it in terms of part-whole.
In your example you can use a mix of json:",omitempty"
tag and "field shadowing" to get the result:
type Parent struct {
Name string `json:"parent_name,omitempty"`
}
type Child struct {
Parent
Name string `json:"child_name"`
}
Playground: http://play.golang.org/p/z72dCKOhYC.
But this still misses the point (and breaks if child.Parent.Name
isn't empty). If you're going to "override" a field in every struct that embeds Parent
, why is it even there in the first place?