In standard library, I can do JSON conversion to a typed object using pointer. The question now is, how do I create a similar method like json.Marshal
to convert an v interface{}
to typed object? Do I need to use reflect
in doing this?
Please see below code snippets, and I am looking for somebody who could fill in the TODO
in the home
package. Thank you.
package main
import (
"encoding/json"
"fmt"
"./home"
)
type Dog struct {
Name string
FavoriteGame string
}
func (dog Dog) Greet() {
dog.Bark()
}
func (dog Dog) Bark() {
if len(dog.Name) == 0 {
panic("This dog has no name!")
}
fmt.Printf("%s < Wo! Wo! %s!
", dog.Name, dog.FavoriteGame)
}
type Cat struct {
Name string
FavoriteMeat string
}
func (cat Cat) Greet() {
cat.Purr()
}
func (cat Cat) Purr() {
if len(cat.Name) == 0 {
panic("This cat has no name!")
}
fmt.Printf("%s < purrrrrrr... %s...
", cat.Name, cat.FavoriteMeat)
}
func main() {
// JSON decoder works here
j := []byte(`{"Name": "Jack", "FavoriteGame": "Swim"}`)
var jack Dog
json.Unmarshal(j, &jack)
jack.Bark()
// Similarly, how do I implement `home` to make the below work?
dogHome := home.Home{Dog{Name: "Bullet", FavoriteGame: "Catch The Ball"}}
var bullet Dog
dogHome.GetPet(&bullet)
bullet.Bark()
catHome := home.Home{Cat{Name: "Ball", FavoriteMeat: "Tuna"}}
var ball Cat
catHome.GetPet(&ball)
ball.Purr()
}
The other package:
package home
type Pet interface {
Greet()
}
type Home struct {
Pet Pet
}
func (h Home) GetPet(v interface{}) {
// TODO: What should I do here?
v = h.Pet
}