Let's say I have two structs:
type Pet {
Name string
}
type PetTwo {
Name string
}
Now let's say that I convert Pet to an interface. How can I Type Assert PetTwo from the interface assuming that the package with which I am doing this from has no knowledge of the Pet type?
var ctx context.Context
pet := Pet{ Name : "Foo" }
ctx = context.WithValue(ctx, "pet", pet)
petTwo := ctx.Value("pet").(PetTwo) // panics
fmt.Println(petTwo.Name) // prints "Foo"
Is there a way I can access the contents of pet without a type assertion?
I've tried to embed the structs in each other, type assertions, type assertions to unnamed types and more.
The main goal is to be able to access the contents of Pet
from a package with no knowledge of the Pet
type.
An ugly hack that achieves the goal is to marshal and unmarshal from json:
jsonData, _ := json.Marshal(ctx.Value("pet"))
var petTwo PetTwo
json.Unmarshal(jsonData, &petTwo)
fmt.Println(petTwo.Name) // prints "Foo"