I have the following struct in my package.
type Animal struct {
Id string
// and some more common fields
}
A user who uses my package should be able to implement own Animal
s. As I need Id
in one of my methods the user has to embed my struct.
type Dog struct {
Animal
Name string
Legs int
}
In my package I have a save()
function that saves Animal
s to database. As I don't know the user's type I have to use interface{}
as argument type. My question is: How do I get the Id
(from the parent struct Animal
)? At the moment I use some JSON parsing and unmarshalling, but is this the way to go/Go?
func put(doc interface{}) error {
res, err := json.Marshal(doc)
if err != nil {
return err
}
var animal *Animal
err = json.Unmarshal(res, &animal)
if err != nil {
return err
}
fmt.Println(animal.Id) // finally I have the Id
// ...
}
Usage
func main() {
bello := Dog{
Animal: Animal{
Id: "abcd1234",
},
Name: "bello",
Legs: 4,
}
err := put(bello)
// ...
}