Reputation: 1459
In my understanding, there is no inherent and polymorphism in golang, so how to get the sub-struct from a given struct? For example, struct A has several attributes:
type A struct {
a int
b string
c *float64
d []byte
e map[string]interface{}
}
I want to delete the e
:
type B struct {
a int
b string
c *float64
d []byte
}
So is there any way to convert A to B except copy variables one by one?
Upvotes: 0
Views: 1643
Reputation: 4421
You can do that with embedded fields. See Struct Types in the Go Language Specification, e.g.:
Field names may be specified explicitly (IdentifierList) or implicitly (EmbeddedField).
With an embedded field, you can copy the fields in one struct to the struct in which it is an embedded field with a simple assignment to the field.
Here's a complete, runnable example:
package main
import (
"encoding/json"
"fmt"
)
type Shared struct {
Id int
Name string
}
type A struct {
Count int
Shared
}
type B struct {
Color string
Shared
}
func main() {
shared := Shared{
Id: 1,
Name: "john",
}
a := A{
Count: 5,
Shared: shared,
}
b := B{
Color: "green",
}
b.Shared = a.Shared
c := map[string]interface{}{
`a`: a,
`b`: b,
}
msg, err := json.Marshal(c)
if err != nil {
fmt.Printf("Marshal error: %s\n", err)
}
fmt.Println(string(msg))
}
Prints:
{"a":{"Count":5,"Id":1,"Name":"john"},"b":{"Color":"green","Id":1,"Name":"john"}}
Upvotes: 2